matplotlib: Drawing charts with Python
In short: matplotlib is the standard library for charts in Python: lines, bars, scatter plots and more, directly from lists or pandas tables.
In more detail: Numbers become understandable only through pictures. matplotlib produces charts for reports, notebooks and publications. seaborn (nicer statistical charts) and the plot functions of pandas build on it.
In Depth
First chart
import matplotlib.pyplot as plt
months = ["Jan", "Feb", "Mar", "Apr"]
revenue = [120, 150, 90, 180]
fig, ax = plt.subplots(figsize=(6, 3))
ax.plot(months, revenue, marker="o", label="Revenue")
ax.set_title("Revenue per month")
ax.set_xlabel("Month")
ax.set_ylabel("Euro")
ax.grid(True, alpha=0.3)
ax.legend()
fig.savefig("revenue.png", dpi=150, bbox_inches="tight")
plt.show()With fig, ax = plt.subplots() you work object-oriented (recommended): fig is the figure, ax the drawing area.
Important chart types
- Line
ax.plot: trends over time. - Bar
ax.bar/ax.barh: compare categories. - Scatter
ax.scatter: relationship of two quantities. - Histogram
ax.hist: distribution of values. - Box plot
ax.boxplot: spread and outliers. - Pie
ax.pie: shares (use sparingly, bars are usually more legible). - Several panels:
plt.subplots(2, 2).
With pandas
import pandas as pd
df = pd.read_csv("sales.csv")
df.groupby("month")["revenue"].sum().plot(kind="bar")Often it takes one line. For interactive charts there are Plotly, Altair, Bokeh; in the browser Chart.js or D3 are suitable.
Good charts
Label axes (with units), choose a clear title, use colours sparingly and colour-blind-friendly, start bar charts at zero, avoid cluttered grids and 3D effects and show one message per chart. Save figures in sufficient resolution or as SVG/PDF (vector-based).
See also: Data visualisation, pandas, Conda and Jupyter, SVG vector graphics