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() and plot.barh() even work directly with a labeled Series or
DataFrame: 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
Section titled “Basic bar chart”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
Section titled “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
Section titled “Horizontal bars”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
Section titled “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:
Start y-axis at 0 for bar charts to avoid misleading comparisons.
Continue to Histogram to visualize the distribution of a single numeric column.
🧪 Try It Yourself
Section titled “🧪 Try It Yourself”Exercise 1 – Draw vertical bars
Section titled “Exercise 1 – Draw vertical bars”Exercise 2 – Horizontal bars for long labels
Section titled “Exercise 2 – Horizontal bars for long labels”Exercise 3 – Sort before plotting
Section titled “Exercise 3 – Sort before plotting”pch.coffeeTagline
pch.coffeeCtapch.feedbackHeading
pch.feedbackSubheading