Bar Chart and Horizontal Bar
Bar charts compare a value across discrete categories — each category gets one bar,
and the bar’s height (or length, for horizontal bars) shows its value. As McKinney
notes, plot.bar()plot.bar() and plot.barh()plot.barh() even work directly with a labeled SeriesSeries or
DataFrameDataFrame: the index becomes the category ticks automatically.
flowchart LR
A["Categories + values"] --> B{"Long labels?"}
B -->|No| C["plt.bar() - vertical bars"]
B -->|Yes| D["plt.barh() - horizontal bars"]
C --> E["Sort by value for easy scanning"]
D --> E
Basic bar chart
Bar
import matplotlib.pyplot as plt
cities = ["Pune", "Delhi", "Mumbai", "Bengaluru"]
sales = [120, 180, 90, 160]
plt.figure(figsize=(7, 4))
plt.bar(cities, sales)
plt.title("Sales by city")
plt.xlabel("City")
plt.ylabel("Sales")
plt.xticks(rotation=20)
plt.tight_layout()
plt.show()Bar
import matplotlib.pyplot as plt
cities = ["Pune", "Delhi", "Mumbai", "Bengaluru"]
sales = [120, 180, 90, 160]
plt.figure(figsize=(7, 4))
plt.bar(cities, sales)
plt.title("Sales by city")
plt.xlabel("City")
plt.ylabel("Sales")
plt.xticks(rotation=20)
plt.tight_layout()
plt.show()Sorted bars
Sorted bars
import matplotlib.pyplot as plt
data = {"Pune": 120, "Delhi": 180, "Mumbai": 90, "Bengaluru": 160}
items = sorted(data.items(), key=lambda x: x[1], reverse=True)
labels = [k for k, _ in items]
values = [v for _, v in items]
plt.figure(figsize=(7, 4))
plt.bar(labels, values)
plt.title("Sales by city (sorted)")
plt.tight_layout()
plt.show()Sorted bars
import matplotlib.pyplot as plt
data = {"Pune": 120, "Delhi": 180, "Mumbai": 90, "Bengaluru": 160}
items = sorted(data.items(), key=lambda x: x[1], reverse=True)
labels = [k for k, _ in items]
values = [v for _, v in items]
plt.figure(figsize=(7, 4))
plt.bar(labels, values)
plt.title("Sales by city (sorted)")
plt.tight_layout()
plt.show()Horizontal bars
Horizontal bar
import matplotlib.pyplot as plt
labels = ["Very long category A", "Long B", "C"]
values = [12, 19, 7]
plt.figure(figsize=(7, 4))
plt.barh(labels, values)
plt.title("Horizontal bar chart")
plt.xlabel("Value")
plt.tight_layout()
plt.show()Horizontal bar
import matplotlib.pyplot as plt
labels = ["Very long category A", "Long B", "C"]
values = [12, 19, 7]
plt.figure(figsize=(7, 4))
plt.barh(labels, values)
plt.title("Horizontal bar chart")
plt.xlabel("Value")
plt.tight_layout()
plt.show()Visualize it
Watch each category’s bar grow to its value — the tallest bar is the easiest to spot because bars share the same zero baseline:
Tip
Start y-axis at 0 for bar charts to avoid misleading comparisons.
Next
Continue to Histogram to visualize the distribution of a single numeric column.
🧪 Try It Yourself
Exercise 1 – Draw vertical bars
Exercise 2 – Horizontal bars for long labels
Exercise 3 – Sort before plotting
If this helped you, consider buying me a coffee ☕
Buy me a coffeeWas this page helpful?
Let us know how we did
