HomeCourseModule 11 › Matplotlib basics

Matplotlib basics

Module 11 · Data Visualization8 min readBeginner

What you'll learn

  • Create a figure and axes
  • Plot lines, bars, and scatter
  • Save the chart to PNG

The basic shape

import matplotlib.pyplot as plt

fig, ax = plt.subplots(figsize=(7, 4))
ax.plot([1, 2, 3, 4], [10, 25, 20, 35])
ax.set_title("My first chart")
ax.set_xlabel("Quarter")
ax.set_ylabel("Revenue")
plt.tight_layout()
plt.savefig("chart.png", dpi=150)
plt.show()

Every chart you make will follow this skeleton: build a figure, draw onto axes, label, save/show.

Three chart types in three lines

ax.plot(x, y)           # line
ax.bar(categories, values)  # bar
ax.scatter(x, y)        # scatter

Style sample

ax.plot(x, y, color="#217346", linewidth=2, marker="o")
ax.grid(alpha=0.3)
ax.spines[["top","right"]].set_visible(False)   # cleaner look

Walkthrough: monthly trend

Data

months = ["Jan","Feb","Mar","Apr","May","Jun"]
revenue = [12, 15, 18, 14, 22, 27]

Plot

fig, ax = plt.subplots(figsize=(7, 3.5))
ax.plot(months, revenue, marker="o", color="#2b6cb0", linewidth=2)
ax.set_title("Monthly Revenue (in thousands)")
ax.set_ylabel("$k")
ax.grid(alpha=0.3)
ax.spines[["top","right"]].set_visible(False)
plt.tight_layout()
plt.savefig("monthly_revenue.png", dpi=150)

Key takeaways

  • fig, ax = plt.subplots(figsize=(w, h)) is the starting point.
  • ax.plot / ax.bar / ax.scatter are the three you'll use most.
  • Always set a title and axis labels. Save with plt.savefig(..., dpi=150).

Bar chart

Make a bar chart of the same monthly revenue data. Make Jan and Feb grey, the other months green.

📹 Video walkthrough
A video walkthrough of this lesson will be embedded here. Until then, the written walkthrough above mirrors what the video will cover step-for-step.