#
Plotting
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
#
Vanilla matplotlib
data = np.arange(10)
plt.plot(data)
[<matplotlib.lines.Line2D at 0x26ee1afada0>]
# Subplots
# subplot(rows, cols, index)
# subplots preferred over plt.plot()
fig = plt.figure()
ax1 = fig.add_subplot(2, 2, 1)
ax2 = fig.add_subplot(2, 2, 2)
ax3 = fig.add_subplot(2, 2, 3) # All 3 should be in the same cell
ax3.plot(np.random.standard_normal(50).cumsum(),
linestyle="dashed")
ax1.hist(np.random.standard_normal(100), bins=20, alpha=0.3)
ax2.scatter(np.arange(30), np.arange(30) + 3 * np.random.standard_normal(30))
<matplotlib.collections.PathCollection at 0x26ee1d750f0>
plt.subplots(2, 3, sharex=True, sharey=True) # share shares axis
plt.subplots_adjust(right=2, top=2)
# Styling
# Add ; to ignore text output
# All methods act on the active or most recently created subplot
plt.plot(np.random.standard_normal(30).cumsum(), color="cyan",
linestyle="dashed", marker="o", label="Hello")
plt.title("HELLO")
plt.xlabel("x")
plt.ylabel("y")
plt.xticks(range(0, 36, 5)) # x spacing & numbers
plt.legend() # enabled by plot labels
plt.text(20, -1, "HAHAH")
plt.annotate("he", (10, 0.0), arrowprops=dict(facecolor="green", headwidth=4, width=2,
headlength=4),) # annotate a point
Text(10, 0.0, 'he')
# Shapes
fig, ax = plt.subplots()
rect = plt.Rectangle((0.2, 0.75), 0.4, 0.15, color="white", alpha=0.3)
circ = plt.Circle((0.7, 0.2), 0.15, color="blue", alpha=0.3)
pgon = plt.Polygon([[0.15, 0.15], [0.35, 0.4], [0.2, 0.6]],
color="green", alpha=0.5)
ax.add_patch(rect)
ax.add_patch(circ)
ax.add_patch(pgon)
<matplotlib.patches.Polygon at 0x26ee1ddff40>
# Configure matplotlib
plt.rc(...)
# DataFrame plotting
df = pd.DataFrame(np.random.standard_normal((10, 4)).cumsum(0),
columns=["A", "B", "C", "D"],
index=np.arange(0, 100, 10))
df.plot.kde()
<Axes: ylabel='Density'>
# Barplot
df = pd.DataFrame(np.random.uniform(size=(6, 4)),
index=["one", "two", "three", "four", "five", "six"],
columns=pd.Index(["A", "B", "C", "D"], name="Genus"))
df.plot.bar()
<Axes: >
df.plot.bar(stacked=True)
<Axes: >
#
Seaborn
sns.barplot(data=df, y="A", orient="h")
c:\Users\ragas\anaconda3\lib\site-packages\seaborn\_oldcore.py:1592: UserWarning: Horizontal orientation ignored with only `y` specified.
warnings.warn(single_var_warning.format("Horizontal", "y"))
<Axes: ylabel='A'>
# Histogram
comp1 = np.random.standard_normal(200)
comp2 = 10 + 2 * np.random.standard_normal(200)
values = pd.Series(np.concatenate([comp1, comp2]))
sns.histplot(values, bins=100)
<Axes: ylabel='Count'>
# Scatterplots
sns.regplot(data=df, x="A", y="B")
<Axes: xlabel='A', ylabel='B'>
sns.pairplot(data=df)
<seaborn.axisgrid.PairGrid at 0x26ee51042e0>