← Back to Python Course | Chapter 13: Data Science & Web | Lesson 6 of 14

Python Data Visualization

Drawing Bar Charts

plt.bar() draws vertical bars (or plt.barh() for horizontal ones) with height proportional to each category's value, making bar charts the natural choice whenever you're comparing a handful of discrete categories against each other.

Example: Drawing Bar Charts

python
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt

plt.bar(["A", "B", "C"], [10, 20, 15])
plt.savefig("bar.png")

Drawing Scatter Plots

plt.scatter() plots each data point individually as a dot positioned by its x and y values, without connecting them with a line. This makes scatter plots the standard way to visually check whether two numeric variables appear correlated.

Example: Drawing Scatter Plots

python
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt

plt.scatter([1, 2, 3], [4, 1, 5])
plt.savefig("scatter.png")

Drawing Histograms

plt.hist() sorts continuous numeric data into a set of ranges called bins and draws a bar for each bin's count, revealing the overall shape of a distribution -- whether it's roughly symmetric, skewed, or has multiple peaks -- in a way a raw list of numbers never could.

Example: Drawing Histograms

python
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt

plt.hist([1, 2, 2, 3, 3, 3, 4])
plt.savefig("hist.png")

Drawing Pie Charts

plt.pie() draws each category as a proportional wedge of a circle, sized by its share of the total. Pie charts work best with a small number of categories that clearly sum to a meaningful whole; too many slices makes the chart cluttered and hard to compare accurately.

Example: Drawing Pie Charts

python
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt

plt.pie([30, 20, 50], labels=["A", "B", "C"])
plt.savefig("pie.png")

Creating Subplots

plt.subplots(rows, cols) creates a grid of independent axes within one figure, letting you display several related charts side by side for direct comparison instead of generating separate images that the viewer has to mentally line up.

Example: Creating Subplots

python
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt

fig, axes = plt.subplots(1, 2)
axes[0].plot([1, 2, 3])
axes[1].bar(["A", "B"], [5, 10])
plt.savefig("subplots.png")

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.