🎉 Welcome to PyVerse! Start Learning Today

PYTHONDATA SCIENCE

Introduction to Matplotlib and Basic Charts

INTRODUCTION TO MATPLOTLIB AND BASIC CHARTS

What You'll Learn

  • What Matplotlib is and why it's useful
  • How to install and import Matplotlib
  • How to make basic charts: line chart, bar chart, and scatter plot
  • How to add titles, labels, colors, and save your chart as an image
  • A short hands-on exercise to practice

Why Charts Matter

Charts turn numbers into pictures your brain understands quickly. Whether you're tracking daily temperature, comparing favorite snacks, or seeing if more study time leads to better scores, charts help you spot patterns fast. Matplotlib is a powerful Python tool that helps you create those charts easily.

What Is Matplotlib?

  • Matplotlib is a Python library for drawing charts and graphs.
  • We'll use its pyplot module, commonly imported as plt.
  • Think of it like a digital graph paper where you tell Python what to draw.

Getting Ready (Install and Import)

  • If you're using a local setup (like VS Code or terminal):
    • Run: pip install matplotlib
  • If you're in Jupyter Notebook:
    • Run in a cell: %pip install matplotlib

Then import it in your Python file or notebook:

import matplotlib.pyplot as plt

Your First Chart: A Line Chart (Step-by-Step)

We'll plot daily temperatures across a week.

import matplotlib.pyplot as plt # 1) Prepare your data days = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"] temps_c = [18, 20, 22, 24, 23, 21, 19] # temperatures in °C # 2) Create a figure (optional: set size) plt.figure(figsize=(8, 5)) # 3) Plot a line chart plt.plot(days, temps_c, color="royalblue", marker="o", # show dots at each point linewidth=2, label="Temp (°C)") # 4) Add labels, title, grid, legend plt.xlabel("Day of the Week") plt.ylabel("Temperature (°C)") plt.title("Weekly Temperatures in My City") plt.grid(True, linestyle="--", alpha=0.5) plt.legend() # 5) Show the chart plt.show()

What happened here:

  • We gave Matplotlib x-values (days) and y-values (temperatures).
  • We customized color, markers, and added helpful labels and a title.
  • grid(True) adds easy-to-read background lines.

Bar Charts: Comparing Categories

Bar charts are perfect for comparing counts (like survey results).

import matplotlib.pyplot as plt # 1) Data: favorite fruits survey fruits = ["Apple", "Banana", "Grapes", "Mango", "Orange"] votes = [15, 22, 12, 18, 10] # 2) Make the bar chart plt.figure(figsize=(8, 5)) plt.bar(fruits, votes, color=["crimson", "gold", "mediumorchid", "darkorange", "deepskyblue"]) # 3) Add labels and title plt.xlabel("Fruit") plt.ylabel("Number of Votes") plt.title("Favorite Fruits in Our Class") # 4) Show the chart plt.show()

Tips:

  • Bar charts are best when your x-values are categories (words), not numbers.
  • You can use one color for all bars or a different color for each.

Scatter Plots: Seeing Patterns

Scatter plots are great for spotting relationships (for example, studying more might lead to higher scores).

import matplotlib.pyplot as plt # 1) Data: hours studied vs test scores (fake but realistic) hours = [1, 2, 3, 3.5, 4, 5, 6, 7, 8] scores = [45, 50, 55, 60, 62, 70, 78, 85, 90] # 2) Create scatter plot plt.figure(figsize=(8, 5)) plt.scatter(hours, scores, color="seagreen", s=60, label="Student") # 3) Add labels, title, grid plt.xlabel("Hours Studied") plt.ylabel("Test Score (%)") plt.title("Do More Hours Studied Lead to Higher Scores?") plt.grid(True, linestyle=":", alpha=0.6) plt.legend() # 4) Show the chart plt.show()

What to look for:

If points go up from left to right, that suggests a positive pattern.

Make It Look Nice (Styles, Legends, Saving)

Here's a quick example using a style and saving your chart as an image file.

import matplotlib.pyplot as plt # Optional: pick a built-in style for a different look plt.style.use("ggplot") # try "ggplot", "seaborn-whitegrid", or "classic" # Data months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun"] rain_mm = [50, 42, 60, 75, 90, 65] plt.figure(figsize=(7, 4)) plt.plot(months, rain_mm, color="navy", marker="s", linestyle="-.", linewidth=2, label="Rainfall (mm)") plt.xlabel("Month") plt.ylabel("Rainfall (mm)") plt.title("Monthly Rainfall") plt.legend() plt.tight_layout() # neat spacing # Save the chart as a PNG image (do this before or after show in most setups) plt.savefig("monthly_rainfall.png", dpi=150, bbox_inches="tight") plt.show()

Notes:

  • plt.style.use changes the overall look.
  • plt.savefig creates an image file you can share. dpi controls clarity.

Common Mistakes and Quick Fixes

  • Problem: ImportError: No module named matplotlib
    • Fix: Install it with pip install matplotlib (or %pip install matplotlib in a notebook)
  • Problem: ValueError about shapes/lengths
    • Fix: Make sure your x and y lists have the same length
  • Problem: Nothing shows up
    • Fix: Call plt.show() at the end (especially in .py files)
  • Problem: Labels overlap
    • Fix: Use plt.tight_layout() to auto-fix spacing

Practical Exercise (Your Turn!) 🎨

Make your own mini data story using Matplotlib.

Task A: Bar Chart

  • Choose 5 school subjects (for example: Math, Science, English, Art, PE).
  • Make up the number of hours you studied each last week (5 numbers).
  • Create a bar chart:
    • x-axis: subject names
    • y-axis: hours studied
    • Add a title, x/y labels, and pick colors
    • Add a grid if you like

Task B: Line or Scatter (choose one)

  • Line chart idea: Track your daily screen time (minutes) for 7 days.
  • Scatter plot idea: Compare minutes of exercise vs energy level (scale 1–10) for 7 days.
  • Add markers, labels, a title, and a legend if needed.

Bonus:

  • Try a different style (like "ggplot").
  • Save your favorite chart as "my_chart.png" using plt.savefig.

Hint starters (replace with your own data):

subjects = ["Math", "Science", "English", "Art", "PE"] hours = [3, 2, 1, 2, 4] plt.figure(figsize=(8, 5)) plt.bar(subjects, hours, color="teal") plt.xlabel("Subject") plt.ylabel("Hours Studied") plt.title("My Study Time Last Week") plt.grid(True, axis="y", alpha=0.3) plt.show()

Recap

  • Matplotlib helps you turn data into clear, colorful charts.
  • Use plt.plot for line charts, plt.bar for bar charts, and plt.scatter for scatter plots.
  • Always label axes and add a title so your chart tells a story.
  • Customize with colors, markers, styles, and grids.
  • Save your charts with plt.savefig to share or use in reports.

You're now ready to explore your own data and make it shine with Matplotlib! 

Loading quizzes...