Introduction to Matplotlib
Matplotlib is Python's most widely used library for creating static, animated, and interactive visualizations — plots, charts, and graphs.
Installing and Importing
pip install matplotlib
import matplotlib.pyplot as plt
Bar Graphs
Bar graphs compare categorical data using rectangular bars.
import matplotlib.pyplot as plt
subjects = ["Python", "DBMS", "OS", "DSA"]
marks = [88, 76, 82, 91]
plt.bar(subjects, marks, color="skyblue")
plt.xlabel("Subject")
plt.ylabel("Marks")
plt.title("Marks by Subject")
plt.show()
Horizontal bar graph
plt.barh(subjects, marks, color="orange")
plt.xlabel("Marks")
plt.title("Marks by Subject (Horizontal)")
plt.show()
Grouped bar chart (comparing two students)
import numpy as np
x = np.arange(len(subjects))
width = 0.35
plt.bar(x - width/2, [88, 76, 82, 91], width, label="Riya")
plt.bar(x + width/2, [75, 80, 70, 85], width, label="Amit")
plt.xticks(x, subjects)
plt.legend()
plt.title("Marks Comparison")
plt.show()
---
Pie Charts
Pie charts show data as proportions of a whole (percentages of a circle).
import matplotlib.pyplot as plt
grades = ["A+", "A", "B", "C"]
counts = [15, 25, 40, 20]
plt.pie(counts, labels=grades, autopct="%1.1f%%", startangle=90)
plt.title("Grade Distribution")
plt.axis("equal") # keeps the pie perfectly circular
plt.show()
Pie chart with an exploded slice (highlighting)
explode = (0.1, 0, 0, 0) # "pull out" the first slice
plt.pie(counts, labels=grades, autopct="%1.1f%%", explode=explode, shadow=True)
plt.title("Grade Distribution (Highlighted)")
plt.show()
Common plt functions
| Function | Purpose |
|---|---|
plt.bar() / plt.barh() | Vertical / horizontal bar chart |
plt.pie() | Pie chart |
plt.plot() | Line chart |
plt.xlabel() / plt.ylabel() | Axis labels |
plt.title() | Chart title |
plt.legend() | Show legend for labeled series |
plt.show() | Render/display the figure |
plt.savefig("file.png") | Save the chart to an image file |