TExcelTAD
Home › Matplotlib › Matplotlib Bars

Matplotlib Bars

Bar charts compare amounts across categories: sales per product, votes per party, bugs per module. Matplotlib draws vertical bars with bar() and horizontal bars with barh().

Vertical bars

plt.bar(categories, heights) draws one bar per category:

python · try it yourself
import matplotlib.pyplot as plt

flavours = ["Vanilla", "Chocolate", "Strawberry", "Mint", "Lemon"]
scoops = [124, 168, 87, 52, 64]

bars = plt.bar(flavours, scoops)
plt.title("Ice cream scoops sold on Saturday")
plt.ylabel("Scoops")
plt.show()

print("Bars drawn:", len(bars))
print("Best seller:", flavours[scoops.index(max(scoops))])
Bars drawn: 5
Best seller: Chocolate

bar() returns a BarContainer, a list-like collection of the rectangle objects.

Tip: Bars encode values by their length, so the value axis of a bar chart should start at zero. Matplotlib does this automatically; don't override it with ylim.

Horizontal bars

Horizontal bars are easier to read when the category names are long or when there are many categories. Sorting the data makes a ranking obvious:

python · try it yourself
import matplotlib.pyplot as plt

languages = {"Python": 49, "JavaScript": 62, "SQL": 51, "TypeScript": 38, "Java": 30, "C#": 27}
ranked = sorted(languages.items(), key=lambda kv: kv[1])
names = [name for name, _ in ranked]
share = [value for _, value in ranked]

plt.barh(names, share, color="C2")
plt.xlabel("Developers using it (%)")
plt.title("Language popularity (made-up survey)")
plt.tight_layout()
plt.show()

print("Top:", names[-1], share[-1], "%")
Top: JavaScript 62 %

barh draws the first item at the bottom, so sorting in ascending order puts the largest bar on top.

Colour, width and labels

Argument bar() barh()
Thickness of bars width=0.8 height=0.8
Fill colour color= (one or a list) color=
Outline edgecolor=, linewidth= same
Stacking offset bottom= left=

plt.bar_label() writes the value on (or in) each bar, which often replaces the need for gridlines:

python · try it yourself
import matplotlib.pyplot as plt

teams = ["Red", "Blue", "Green", "Gold"]
points = [18, 25, 21, 9]
colors = ["#d62728", "#1f77b4", "#2ca02c", "#bcbd22"]

bars = plt.bar(teams, points, color=colors, width=0.6, edgecolor="black")
plt.bar_label(bars, padding=3)
plt.ylim(0, 30)
plt.title("League points")
plt.show()

print("Bar width:", bars[0].get_width())
print("Heights:", [int(b.get_height()) for b in bars])
Bar width: 0.6
Heights: [18, 25, 21, 9]

Grouped bars

To compare two series per category, shift each series sideways by half a bar width. Use NumPy positions instead of the category strings, then put the names back with xticks:

python · try it yourself
import numpy as np
import matplotlib.pyplot as plt

quarters = ["Q1", "Q2", "Q3", "Q4"]
online = np.array([120, 135, 160, 190])
store = np.array([150, 140, 145, 170])

x = np.arange(len(quarters))
w = 0.38

plt.bar(x - w / 2, online, width=w, label="Online")
plt.bar(x + w / 2, store, width=w, label="In store")
plt.xticks(x, quarters)
plt.ylabel("Orders")
plt.legend()
plt.title("Orders per quarter")
plt.show()

print("Online beats store in:", [q for q, a, b in zip(quarters, online, store) if a > b])
Online beats store in: ['Q3', 'Q4']

Stacked bars

Stacked bars show a total and how it is composed. Each extra layer uses bottom= set to the sum of the layers below it:

python · try it yourself
import numpy as np
import matplotlib.pyplot as plt

days = ["Mon", "Tue", "Wed", "Thu", "Fri"]
coffee = np.array([40, 42, 38, 45, 50])
tea = np.array([15, 18, 20, 16, 14])
juice = np.array([10, 8, 12, 9, 20])

plt.bar(days, coffee, label="Coffee")
plt.bar(days, tea, bottom=coffee, label="Tea")
bars = plt.bar(days, juice, bottom=coffee + tea, label="Juice")
plt.bar_label(bars)          # labels on the top layer show the stack top = total
plt.ylabel("Drinks sold")
plt.legend(loc="upper left")
plt.ylim(0, 100)
plt.show()

print("Totals:", (coffee + tea + juice).tolist())
Totals: [65, 68, 70, 70, 84]

Test yourself

Which function draws horizontal bars?

  1. plt.hbar()
  2. plt.barh()
  3. plt.bar(horizontal=True)
  4. plt.bars()

How do you stack a second series on top of the first in a bar chart?

  1. stack=True
  2. Call bar() twice with the same values
  3. Pass bottom= with the heights of the first series
  4. Use plt.stack()

What does plt.bar_label(bars) do?

  1. Adds a legend
  2. Writes each bar's value next to it
  3. Renames the categories
  4. Sorts the bars