Bar Charts (matplotlib)
๐จ๐ Technique Card: Bar Charts using matplotlib (practical)
๐ก What This Lets You Do
Create simple bar charts to visually compare data. Great for showing totals, categories, and differences.
๐งฐ You'll Need
- Python installed
matplotlibinstalled (pip install matplotlibif needed)
๐ช Code Example: A Simple Bar Chart
import matplotlib.pyplot as plt
# Data
categories = ["Apples", "Bananas", "Cherries"]
quantities = [10, 15, 7]
# Create bar chart
plt.bar(categories, quantities)
# Add labels
plt.title("Fruit Sold Today")
plt.xlabel("Fruit")
plt.ylabel("Quantity")
# Show chart
plt.show()
๐ Key Parts Explained
| Code | What It Does |
|---|---|
import matplotlib.pyplot as plt |
Brings in the chart-making tools |
plt.bar() |
Makes a bar chart |
plt.title(), xlabel(), ylabel() |
Adds labels |
plt.show() |
Displays the chart in a window or output cell |
๐ ๏ธ Try This
Change the values in categories and quantities to match your own data (like food miles, recycling totals, etc.).
๐ฏ Mini Challenges
- Create a bar chart showing how many children cycle, walk, or drive to school.
- Try changing the colours using
color=["red", "yellow", "pink"]. - Sort your data so the tallest bar is first.
๐ Using Data from a CSV with Pandas and Plotting with Matplotlib
You can load data from a .csv file using pandas, then select the columns you want to plot and assign them to x and y variables for clarity.
๐งช Example Code
import pandas as pd
import matplotlib.pyplot as plt
# Read data from a CSV file
df = pd.read_csv("fruit_sales.csv")
# Prepare x and y data from specific columns in the DataFrame
x = df["Fruit"]
y = df["Sold"]
# Create a bar chart
plt.bar(x, y)
# Add labels and a title
plt.title("Fruit Sold Today")
plt.xlabel("Fruit")
plt.ylabel("Quantity")
plt.show()
๐ Example CSV File (fruit_sales.csv)
| Fruit | Sold |
|---|---|
| Apples | 12 |
| Bananas | 18 |
| Oranges | 9 |
โ Tips
- Make sure your
.csvfile is saved in the same folder as your Python script, or provide the full path to the file. - Your column names in the
.csvmust match exactly what you type in your code ("Fruit"and"Sold"in this example).
๐ Linked Cards
- ๐ Technique Card: Reading CSV Files with Pandas (practical)
- ๐ Technique Card: Working With CSV Files (practical)
- ๐ Technique Card: Percentages (deeper)
- ๐ Technique Card: Telling Stories With Data (deeper)
