Python Line, Bar, Scatter and Histogram Charts

Match each data question to a line, bar, scatter or histogram chart, and draw it honestly with Matplotlib.

Lesson 80 of 107Advanced12 min read

Four chart types answer most data questions:

QuestionChartMatplotlib
How did something change over time?lineax.plot(x, y)
How do categories compare?barax.bar(categories, values)
Are two measurements related?scatterax.scatter(x, y)
How are values distributed?histogramax.hist(values, bins=...)

Choosing the wrong one can mislead even when every number is correct. This lesson explains what each chart shows, when to use it, and the settings, such as baselines and bin widths, that change what readers see. The examples come from a community garden tracking attendance, harvests and plant growth. They build on the Matplotlib tutorial, which covers figures, axes, labels and saving.

Line charts

A line connects observations in order, so the slope between points shows change. Use it when the x axis is a meaningful sequence: dates, weeks, temperatures, positions.

Python
weeks = [1, 2, 3, 4, 5, 6]
volunteers = [14, 18, 17, 22, 25, 21]
ax.plot(weeks, volunteers, marker="o")
ax.set(xlabel="Week", ylabel="Volunteers (people)", title="Garden volunteers per week")

Markers show where the actual measurements are, which matters when observations are irregular or sparse. Several lines on one axes compare trends, as long as there are few enough to tell apart, typically no more than four or five, each with a legend label.

Don't use a line for unordered categories. A line from "beans" to "peas" to "kale" implies a progression between vegetables that doesn't exist; that's a bar chart's job. Line charts may start the y axis above zero when the change itself is the subject, but say so.

Bar charts

Bars compare amounts between categories. The bar's length encodes the value, so the value axis should start at zero:

Python
crops = ["beans", "peas", "kale", "squash"]
harvest_kg = [12, 9, 15, 22]
ax.bar(crops, harvest_kg)
ax.set(ylabel="Harvest (kg)", title="Harvest by crop, 2026")
ax.set_ylim(0, None)

With a baseline at 8 kg instead of 0, the peas' 9 kg bar would look a fraction of the beans' 12 kg bar, exaggerating a modest difference. Matplotlib starts bar axes at zero by default; keep it that way.

Order bars meaningfully, by value for rankings or in a natural order such as months, rather than alphabetically by accident. Use ax.barh() for long labels or many categories. Grouped or stacked bars compare subcategories, but readers struggle beyond a few groups.

Scatter plots

A scatter plot shows pairs of numbers, one point per observation, to reveal whether two measurements are related:

Python
water_litres = [2, 3, 3.5, 4, 5, 6, 6.5, 8]
height_cm = [18, 22, 21, 27, 30, 34, 33, 40]
ax.scatter(water_litres, height_cm)
ax.set(xlabel="Water per week (litres)", ylabel="Plant height (cm)")

A pattern rising from bottom left to top right suggests a positive association: plants that received more water tended to be taller. Look also for clusters, curves and outliers that a single correlation number would hide.

An association isn't proof of cause. The well-watered plants might also be in the sunniest beds, and sunlight could explain both. Scatter plots are excellent for spotting relationships worth investigating; establishing why needs an experiment or careful reasoning about other factors.

Histograms

A histogram shows the distribution of one numeric variable: it divides the range into intervals, called bins, and draws a bar for how many values fall in each.

Python
heights = [15, 18, 18, 22, 25, 27, 28, 29, 31, 33, 34, 36, 41]
ax.hist(heights, bins=5, edgecolor="white")
ax.set(xlabel="Plant height (cm)", ylabel="Number of plants")

It answers questions a summary statistic can't: is the data symmetric or skewed, is there one peak or two, are there outliers?

The number of bins changes the picture. Too few bins hide structure, such as two groups of plants; too many make random noise look like a pattern. Try a few values, or specify bin edges that make sense for the data, such as every 5 cm: bins=range(10, 46, 5). A histogram differs from a bar chart: its x axis is a continuous number line, so bars touch, and their order is fixed by the values.

Independent practice and a worked check

Task: choose and export one chart for each garden question, with units and justified scale and bin settings.

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

heights_cm = [12, 14, 15, 15, 17, 18, 21, 22, 23, 23, 24, 26, 30]
fig, (a, b) = plt.subplots(1, 2, figsize=(9, 4))
a.hist(heights_cm, bins=range(10, 35, 5), edgecolor="white")
a.set(title="Plant heights", xlabel="Height (cm)", ylabel="Plants")
b.hist(heights_cm, bins=2, edgecolor="white")
b.set(title="Same data, 2 bins", xlabel="Height (cm)")
fig.tight_layout()
fig.savefig("bins_comparison.png")
plt.close(fig)

Compare the two panels: 5 cm bins show the shape of the distribution, while two bins hide it. Justify your choice in the caption. For the worked check, the chart that shows the distribution of one numeric variable is the histogram.

Reference and next practice

Matplotlib's plot types gallery shows every chart with code, and its histogram guide covers bins. Continue with time and space complexity or revisit statistics. Practise with the Python exercises and Python quiz.

Line, Bar, Scatter and Histogram Charts Summary

  • Line charts: A line connects ordered observations to reveal changes along a meaningful sequence.
  • Bar charts: Bars compare category values and normally need an appropriate zero baseline.
  • Scatter plots: A scatter plot shows paired numeric observations.
  • Histograms: A histogram groups one numeric variable into intervals to show its distribution.

Line, Bar, Scatter and Histogram Charts Examples

Each example shows the code, the output it produces and what each part does.

Example 1

Line, Bar, Scatter and Histogram Charts in a small program

This saves garden_comparison.png with a bar chart and a histogram side by side; it prints nothing.

Python
import matplotlib.pyplot as plt
fig, axes = plt.subplots(1, 2)
axes[0].bar(["beans", "peas"], [12, 9])
axes[0].set_ylabel("Harvest kg")
axes[1].hist([15, 18, 18, 22, 25, 27], bins=3)
axes[1].set_xlabel("Plant height cm")
fig.tight_layout()
fig.savefig("garden_comparison.png")
plt.close(fig)
Line-by-line explanation
  1. Lines 3 to 4A bar chart compares two crop categories, with the unit in the label.
  2. Lines 5 to 6A histogram groups six plant heights into three bins.
  3. Lines 7 to 9tight_layout() prevents overlapping labels before the figure is saved and closed.
Example 2

Four charts, four questions

Python
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
from statistics import correlation

weeks = [1, 2, 3, 4, 5, 6]
volunteers = [14, 18, 17, 22, 25, 21]
crops, harvest = ["squash", "kale", "beans", "peas"], [22, 15, 12, 9]
water = [2, 3, 3.5, 4, 5, 6, 6.5, 8]
height = [18, 22, 21, 27, 30, 34, 33, 40]

fig, ax = plt.subplots(2, 2, figsize=(10, 7))
ax[0, 0].plot(weeks, volunteers, marker="o")
ax[0, 0].set(title="Trend: volunteers per week", xlabel="Week", ylabel="People")
ax[0, 1].bar(crops, harvest)
ax[0, 1].set(title="Comparison: harvest by crop", ylabel="kg")
ax[1, 0].scatter(water, height)
ax[1, 0].set(title="Relationship: water and height", xlabel="Litres/week", ylabel="cm")
counts, edges, _ = ax[1, 1].hist(height, bins=range(15, 46, 10))
ax[1, 1].set(title="Distribution: plant heights", xlabel="cm", ylabel="Plants")
fig.tight_layout()
fig.savefig("garden_dashboard.png", dpi=110)
plt.close(fig)

print("Bar baseline:", ax[0, 1].get_ylim()[0])
print("Histogram bins:", edges.tolist(), "counts:", counts.astype(int).tolist())
print("Water-height correlation:", round(correlation(water, height), 2))
Output
Bar baseline: 0.0
Histogram bins: [15.0, 25.0, 35.0, 45.0] counts: [3, 4, 1]
Water-height correlation: 0.98
Line-by-line explanation
  1. Line 8Crops are listed largest first, so the bar chart reads as a ranking.
  2. Line 19Explicit 10 cm bin edges make the histogram's grouping deliberate rather than automatic.
  3. Lines 25 to 27Checking the figure confirms the bar baseline is zero and shows how values fell into bins.

Common Line, Bar, Scatter and Histogram Charts Mistakes

A truncated baseline on a bar chart

Don't
ax.bar(["beans", "peas"], [12, 9])
ax.set_ylim(8, 13)         # 12 vs 9 kg looks like 4 vs 1
Do
ax.bar(["beans", "peas"], [12, 9])
ax.set_ylim(0, None)       # bar lengths proportional to the values

Joining categories with a line

Don't
ax.plot(["beans", "peas", "kale"], [12, 9, 15])     # implies a sequence between crops
Do
ax.bar(["beans", "peas", "kale"], [12, 9, 15])

Line, Bar, Scatter and Histogram Charts in Real Projects

Choosing charts in reports

Analysts start every chart from the question, not from the chart type: "has attendance grown?" is a line; "which crop yielded most?" is a sorted bar; "does watering affect growth?" is a scatter; "how big do the plants usually get?" is a histogram. Dashboards combine these, each with a title that states the finding rather than just the variable names.

Good practice includes labelled axes with units, honest baselines, consistent colours for the same category across charts, and a source and date line. pandas (df.plot.bar(), df.plot.hist()), seaborn and Plotly offer the same four chart types with different defaults, so these choices carry over.

Line, Bar, Scatter and Histogram Charts FAQ

Which chart should I use for my data?

Use a line chart for change over an ordered sequence such as time, a bar chart to compare categories, a scatter plot for the relationship between two numeric variables, and a histogram for the distribution of one numeric variable.

What is the difference between a bar chart and a histogram?

A bar chart compares separate categories, which can be reordered. A histogram groups a continuous numeric variable into adjacent intervals, so its bars touch and their order is fixed by the number line.

How many bins should a histogram have?

There's no single right answer. Start with Matplotlib's default or a rule such as bins="auto", then try a few values and choose edges meaningful for the data, such as every 5 cm. Report the choice, because it changes the apparent shape.

Should bar charts always start at zero?

Yes, for the value axis. Bar length encodes the value, so a non-zero baseline distorts comparisons. Line charts can start elsewhere when the change itself is the focus, as long as the axis is clearly labelled.

Does a scatter plot show causation?

No. It shows whether two variables move together. Other factors may cause both, so use it to find relationships worth investigating, and confirm causes with experiments or domain knowledge.

Line, Bar, Scatter and Histogram Charts Exercises

Answer each one and check it instantly. If you get stuck, open the hint before the answer.

Multiple choiceeasy

Which chart shows the distribution of one numeric variable?

Multiple choicemedium

Which review concern is valid for line, bar, scatter and histogram charts?

Line, Bar, Scatter and Histogram Charts Quiz

2 questions to check what you learned.

  1. Which chart shows the distribution of one numeric variable?

    • Category bar chart
    • Histogram
    • Python ignores the distinction
  2. Which statement correctly describes scatter plots?

    • A scatter plot shows paired numeric observations.
    • Only the example output matters, not the rule
    • Every operation has the same behavior