TutorialsPythonMatplotlib Basics

Matplotlib Basics

Create line, bar, and scatter charts — the foundation of Python data visualisation

Matplotlib is the foundational plotting library in Python. Most other libraries (seaborn, pandas .plot()) are built on top of it. Understanding matplotlib's structure makes you better at all Python charting. Key concept: matplotlib has two interfaces: pyplot (quick charts, like MATLAB) and the object-oriented API (Figure and Axes objects). For data analyst work, pyplot is enough for quick exploration; the OO API is used for polished, publication-quality charts.

Example

Common chart types with matplotlib
import matplotlib.pyplot as plt
import numpy as np

# DATA
months = ["Jan","Feb","Mar","Apr","May","Jun"]
sales = [420, 510, 480, 620, 590, 710]
costs = [300, 360, 340, 430, 420, 490]

# LINE CHART
plt.figure(figsize=(10, 5))
plt.plot(months, sales, marker="o", color="#c47f00", label="Sales")
plt.plot(months, costs, marker="s", color="#0284c7", label="Cost")
plt.title("Monthly Sales vs Cost 2026")
plt.xlabel("Month")
plt.ylabel("Amount (₹ thousands)")
plt.legend()
plt.grid(alpha=0.3)
plt.tight_layout()
plt.show()

# BAR CHART
plt.figure(figsize=(8, 5))
bars = plt.bar(months, sales, color="#c47f00", edgecolor="white")
plt.title("Monthly Sales")
plt.ylabel("₹ (thousands)")
# Add value labels
for bar in bars:
    plt.text(bar.get_x() + bar.get_width()/2, bar.get_height() + 10,
             str(int(bar.get_height())), ha="center", fontsize=9)
plt.tight_layout()
plt.show()

Key Points

  • plt.figure(figsize=(width, height)) — always set size before plotting
  • plt.tight_layout() prevents labels from being cut off — always call it before show()
  • marker="o" adds data point markers on line charts
  • plt.savefig("chart.png", dpi=150, bbox_inches="tight") — save for reports
  • In Jupyter: charts appear inline without plt.show(); in scripts you need plt.show()

Practice Question

Which matplotlib function prevents axis labels and titles from being cut off at the edges?