🎉 Welcome to PyVerse! Start Learning Today

PYTHONDATA SCIENCE

Creating Bar, Pie, and Line Graphs

Lesson: Creating Bar, Pie, and Line Graphs

Introduction

Have you ever voted for a favorite snack in class, tracked your weekly screen time, or planned how to spend your allowance? Graphs help turn those numbers into pictures your brain understands fast. In this lesson, you'll learn how to make three popular charts in Python: bar charts, pie charts, and line graphs.

What You'll Need

  • Python installed (any recent version).
  • The matplotlib library (this draws the graphs).
    • Install from a terminal or command prompt: pip install matplotlib
    • In a Jupyter notebook: !pip install matplotlib

When to Use Each Graph

  • Bar Chart: Compare categories (Which fruit got more votes?).
  • Pie Chart: Show parts of a whole (How your budget is split).
  • Line Graph: Show change over time (Temperatures across a week).

Step-by-Step: How to Make Any Graph in Python

  1. Choose your data (simple lists of labels and numbers).
  2. Import matplotlib.
  3. Create a new figure (optional but tidy).
  4. Call the right plot function (bar, pie, or plot).
  5. Add title, axis labels, and (sometimes) a legend.
  6. Show your graph with plt.show().

Python Code Examples

Code Example 1: Bar Chart (Favorite Fruits)

Goal: Compare how many students voted for each fruit.

What this shows:

  • Bars show counts for each fruit.
  • A grid makes numbers easy to read.
  • Labels on top of bars show exact values.
import matplotlib.pyplot as plt # 1) Your data fruits = ['Apples', 'Bananas', 'Grapes', 'Oranges', 'Strawberries'] votes = [12, 20, 7, 10, 15] # 2) Make the figure plt.figure(figsize=(7, 4)) # 3) Draw the bar chart colors = ['#ff9999', '#ffe680', '#c2dfff', '#ffcc99', '#d5a6bd'] bars = plt.bar(fruits, votes, color=colors) # 4) Add title and labels plt.title('Class Favorite Fruits') plt.xlabel('Fruit') plt.ylabel('Number of Votes') # 5) Add a light grid across the y-axis for readability plt.grid(axis='y', linestyle='--', alpha=0.4) # 6) Put the number on top of each bar for bar in bars: height = bar.get_height() plt.text( bar.get_x() + bar.get_width() / 2, # x position (center of bar) height + 0.3, # y position (just above the bar) str(height), # the text to show ha='center', va='bottom' ) # 7) Tidy layout and show plt.tight_layout() plt.show()

Code Example 2: Pie Chart (Simple Monthly Budget)

Goal: Show how a $100 budget is split.

What this shows:

  • Percent labels (autopct) show each slice's share.
  • explode pulls one slice out for emphasis.
  • axis('equal') keeps the pie circular.
import matplotlib.pyplot as plt # 1) Your data categories = ['Food', 'Transport', 'Entertainment', 'Savings'] amounts = [40, 15, 25, 20] # These could be dollars out of $100 # 2) Make the figure plt.figure(figsize=(6, 6)) # 3) Draw the pie chart explode = [0.05, 0, 0, 0] # Slightly "pop out" the first slice colors = ['#66b3ff', '#99ff99', '#ffcc99', '#ff9999'] plt.pie( amounts, labels=categories, autopct='%1.0f%%', # show whole-number percentages startangle=90, # start from the top explode=explode, colors=colors ) # 4) Keep the pie round and add a title plt.axis('equal') plt.title('How I Spend $100 in a Month') plt.tight_layout() plt.show()

Code Example 3: Line Graph (Daily Temperatures)

Goal: Show how temperature changes over a week.

What this shows:

  • Markers highlight each day.
  • A legend explains the line.
  • An annotation points out the highest temperature.
import matplotlib.pyplot as plt # 1) Your data days = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'] temperatures_c = [18, 20, 21, 19, 22, 24, 23] # 2) Make the figure plt.figure(figsize=(7, 4)) # 3) Draw the line chart plt.plot( days, temperatures_c, marker='o', linestyle='-', color='#1f77b4', linewidth=2, label='Temperature (°C)' ) # 4) Add title, labels, grid, and legend plt.title('Daily Temperatures This Week') plt.xlabel('Day') plt.ylabel('Temperature (°C)') plt.grid(linestyle='--', alpha=0.4) plt.legend() # 5) Mark the highest temperature max_temp = max(temperatures_c) max_day = days[temperatures_c.index(max_temp)] plt.text(max_day, max_temp + 0.3, f'High: {max_temp}°C', ha='center') # 6) Show the graph plt.tight_layout() plt.show()

Practical Exercise: Your Turn 🎨

Task A: Bar Chart (Classroom Survey)

  • Ask 5 friends their favorite sport (or snack).
  • Make a bar chart showing how many votes each option got.
  • Requirements:
    • Title, x-label, y-label
    • At least 5 categories
    • Grid on the y-axis
    • Numbers on top of the bars

Task B: Line Graph (One-Week Tracker)

  • Track one thing for 7 days (minutes of reading, steps, screen time).
  • Make a line graph with:
    • Markers on each point
    • A title and labels
    • A grid
    • Optional: annotate the highest value

Bonus: Pie Chart (After-School Time)

  • Choose 3–5 activities (Homework, Gaming, Exercise, Friends).
  • Assign minutes for one day (any numbers; the pie will show percentages).
  • Make a pie chart with labels and percentages.

Common Mistakes and Quick Fixes

  • The bars or line won't show:
    • Add plt.show() at the end.
  • Error: x and y must have same first dimension:
    • Your labels and numbers lists must be the same length.
  • Pie chart looks squished:
    • Add plt.axis('equal').
  • Parts overlap or are cut off:
    • Add plt.tight_layout() before plt.show().

Optional: Save Your Graph as an Image

Add this before plt.show():

# Save as a PNG image file plt.savefig('my_graph.png', dpi=150)

Recap

  • Bar charts compare categories side-by-side.
  • Pie charts show how a whole is divided into parts.
  • Line graphs show change over time.
  • With matplotlib, you choose your data, pick the right chart, add labels and a title, and show it. Try customizing colors, markers, and grids to make your story clear and fun! 

Loading quizzes...