typestar

Bar charts in Python

Categories along one axis, values along the other, labels on the bars.

import matplotlib

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

langs = ["python", "rust", "c", "sql"]
steps = [143, 181, 165, 45]
order = sorted(range(len(steps)), key=lambda i: steps[i], reverse=True)

figure, axes = plt.subplots()
bars = axes.bar([langs[i] for i in order], [steps[i] for i in order],
                color="#7c5cff")
axes.bar_label(bars, padding=2)
axes.set_ylabel("steps")
axes.set_ylim(0, 210)
figure.savefig("bars.png")

How it works

  1. bar is vertical, barh horizontal.
  2. bar_label writes the value on each bar.
  3. Sorting the data first is what makes a bar chart readable.

Keywords and builtins used here

The run, in numbers

Lines
16
Characters to type
436
Tokens
149
Three-star pace
105 tpm

At the three-star pace of 105 tokens a minute, this run takes about 85 seconds.

Type this snippet

Step 3 of 5 in Plot types, step 7 of 14 in Plotting with matplotlib.

← Previous Next →

Bar charts in other languages