Matplotlib
%matplotlib inline
Plots
Image
import matplotlib.pyplot as plt
plt.imshow(arr)
Plot two lines that share the x axis
https://matplotlib.org/gallery/api/two_scales.html
fig, ax1 = plt.subplots()
ax1.plot(x, y, 'r')
ax2 = ax1.twinx()
ax2.plot(x, y, 'b')
If you want the same scale:
ymin, ymax = y.min(), y.max()
ax1.set_ylim(ymin, ymax)
ax2.set_ylim(ymin, ymax)
Subplots
fig = plt.figure()
ax_array = fig.subplots(2, 2)
for i, process in enumerate([0.5, 1]):
for j, noise in enumerate([1, 10]):
r = ...
r.plot(ax=ax_array[i, j])
ax_array[i, j].set_title(f"process={process}, noise={noise}")
fig.tight_layout()
Reverse x axis
ax.invert_xaxis()
Bar Plot
fig = plt.figure(figsize=(8, 3))
plt.bar(x=df_students.Name, height=df_students.Grade, color='orange')
# Customize the chart
plt.title('Student Grades')
plt.xlabel('Student')
plt.ylabel('Grade')
plt.grid(color='#95a5a6', linestyle='--', linewidth=2, axis='y', alpha=0.7)
plt.xticks(rotation=90)
Axis
y ticks
ax.yaxis.set_ticks(np.arange(len(df)) + 1)
Interactive plots
%matplotlib widget
or
%matplotlib ipympl
Parameters
Setup parameters
https://matplotlib.org/3.3.2/tutorials/introductory/customizing.html
import matplotlib as mpl
mpl.rcParams['axes.titlesize'] = 20
mpl.rcParams['axes.labelsize'] = 20
mpl.rcParams['ytick.labelsize'] = 15
mpl.rcParams['xtick.labelsize'] = 15
mpl.rcParams['legend.fontsize'] = 15
Format dates
fig.autofmt_xdate()
Format dollars
import matplotlib.ticker as ticker
revenue_formatter = ticker.StrMethodFormatter('${x:,.0f}')
ax.yaxis.set_major_formatter(revenue_formatter)
Table
fig, ax = plt.subplots(figsize=(12, 4))
ax.axis("tight")
ax.axis("off")
table = ax.table(cellText=df.values, colLabels=df.columns, loc="center")
to pdf
from matplotlib.backends.backend_pdf import PdfPages
pp = PdfPages("file.pdf")
pp.savefig(fig, bbox_inches="tight")
pp.close()