Matplotlib quick reference

Sudheer Keshav Bhat · October 11, 2021

Data Visualization

Create multiple plots within a fig

fig, axes = plt.subplots(no_of_rows, no_of_cols)

Flatten the axes array to ease iteration

flat_axes = np.array(axes).ravel()

Set x & y labels

axis.set(xlabel="date", ylabel="price")

Position legend

axis.legend(bbox_to_anchor=(1.01, 1), borderaxespad=0, loc="upper right")

Draw multiple graph types on the same subplot

ax2 = axis.twinx()

Fix fig size (clipping and/or overflow)

plt.tight_layout()

Save the figure

fig.savefig("plot.png", dpi=100)

Close the plot to release memory

Especially useful when many plots are needed.

plt.close(fig)