🎓 A1Learner
🔍
0 of 50 lessons completed

Bar Charts

A bar chart shows one bar per group. DataFrame.plot draws the chart straight from a frame.

Bars from a frame

Each product gets one bar. The bar height is its units.

import os
import matplotlib.pyplot as plt
import pandas as pd

df = pd.DataFrame({"product": ["Tea", "Coffee", "Mug"], "units": [2, 1, 3]})
df.plot(kind="bar", x="product", y="units")
plt.savefig("chart.png")
print(os.path.getsize("chart.png"))

Bars that lie flat

barh turns the bars sideways. The same columns draw the chart.

import os
import matplotlib.pyplot as plt
import pandas as pd

df = pd.DataFrame({"product": ["Tea", "Coffee", "Mug"], "units": [2, 1, 3]})
df.plot(kind="barh", x="product", y="units")
plt.savefig("chart.png")
print(os.path.getsize("chart.png"))

Bars of money

Revenue is units times price. Each category gets one bar.

import os
import matplotlib.pyplot as plt
import pandas as pd

df = pd.DataFrame({"category": ["Drink", "Home", "Office"], "revenue": [45.0, 120.0, 56.5]})
df.plot(kind="bar", x="category", y="revenue")
plt.savefig("chart.png")
print(os.path.getsize("chart.png"))

Example

import io
import matplotlib.pyplot as plt
import os
import pandas as pd

SALES_CSV = """
order_id,date,product,category,units,price,region
101,2026-01-05,Tea,Drink,2,4.50,North
102,2026-01-06,Coffee,Drink,1,6.00,South
103,2026-01-07,Mug,Home,3,12.00,East
104,2026-01-08,Notebook,Office,2,8.50,West
105,2026-01-09,Pen,Office,5,2.00,North
106,2026-01-12,Lamp,Home,1,24.00,South
107,2026-01-13,Tea,Drink,4,4.50,East
108,2026-01-14,Coffee,Drink,2,6.00,West
109,2026-01-15,Mug,Home,1,12.00,North
110,2026-01-16,Notebook,Office,3,8.50,South
111,2026-01-19,Pen,Office,2,2.00,East
112,2026-01-20,Lamp,Home,2,24.00,West"""

sales = pd.read_csv(io.StringIO(SALES_CSV))
by_category = sales.groupby("category")["units"].sum()
print(by_category)
by_category.plot(kind="bar")
plt.savefig("chart.png")
print(os.path.getsize("chart.png"))

Key points

  • Use df.plot to draw a chart from a frame.
  • Use kind="bar" for bars that stand up.
  • Use kind="barh" for bars that lie flat.
  • The x and y names pick the columns for the bars.
  • A bar chart suits counts and totals by group.

In this example, the sales table loads from its CSV text. groupby adds up the units for each category. The totals print first, then plot draws one bar per category. savefig writes the chart, and getsize prints the file size as proof.

Note

df.plot draws the chart, but savefig still writes the file. A chart without savefig is never saved.

Try it Yourself

Edit the code, then press Run.

Running is simulated · Python Playground

Exercise

Which call draws a bar chart from a frame called df?