Bar charts

Vertical bars, grouped bars, and barh.

Bars compare categories. The x values are names (cities, products), not a continuous axis.

Goal

Draw a simple bar chart, grouped bars, and a horizontal bar chart.

Vertical

cities = ["Nairobi", "Mombasa", "Kisumu"]
totals = [21, 15, 15]
fig, ax = plt.subplots()
ax.bar(cities, totals, color="#1d4f7a")
ax.set_ylabel("units")
ax.set_title("Units by city")
plt.show()

Grouped

cities = ["Nairobi", "Mombasa", "Kisumu"]
a = np.array([12, 9, 3], dtype=float)
b = np.array([7, 6, 11], dtype=float)
x = np.arange(len(cities))
width = 0.38
fig, ax = plt.subplots()
ax.bar(x - width / 2, a, width, label="A")
ax.bar(x + width / 2, b, width, label="B")
ax.set_xticks(x, cities)
ax.set_ylabel("units")
ax.legend()
ax.set_title("Units by city and product")
plt.show()

x is numeric positions; set_xticks puts the names back.

Horizontal

products = ["A", "B", "C"]
sold = [40, 36, 3]
fig, ax = plt.subplots()
ax.barh(products, sold)
ax.set_xlabel("units")
ax.set_title("Units by product")
plt.show()

Long category names fit better on barh.

Pitfall

plt.bar(months, values) with numeric month numbers 1–12 looks like a histogram. Use string labels, or a line plot, when the x-axis is ordered time.