plt.bar() draws bars from category labels and their heights — the standard chart for comparing magnitudes across groups.
A Basic Bar Plot
R Code
import matplotlib.pyplot as plt months = ["Jan", "Feb", "Mar", "Apr"] sales = [120, 150, 90, 170] plt.bar(months, sales, color="steelblue") plt.title("Monthly Sales") plt.ylabel("Units Sold") plt.show()
Bar Plot from Value Counts
R Code
import pandas as pd grades = pd.Series(["A","B","A","C","A","B"]) counts = grades.value_counts() print(counts) counts.plot(kind="bar", color="tomato", title="Grade Distribution") plt.show()
Output
A 3 B 2 C 1 Name: count, dtype: int64
Horizontal Bars
R Code
plt.barh(months, sales, color="darkgreen") plt.show()
Advanced: Grouped Bar Plot
🚀 Advanced Example
Grouped bars need manual x-position offsets in matplotlib - a common pattern worth memorising.R Code
import numpy as np quarters = ["Q1", "Q2", "Q3"] male = [20, 30, 40] female = [35, 25, 20] x = np.arange(len(quarters)) width = 0.35 plt.bar(x - width/2, male, width, label="Male", color="skyblue") plt.bar(x + width/2, female, width, label="Female", color="pink") plt.xticks(x, quarters) plt.legend() plt.show()
Key Points
- plt.bar(labels, heights) draws vertical bars; plt.barh() draws horizontal bars.
- series.value_counts() is the quickest way to get category counts to plot.
- Grouped bars require manually offsetting x-positions using numpy.arange() and a width value.