Skip to main content

Matplotlib: Create Line, Bar, Scatter, and Pie Charts

Intermediate25 min6 exercises90 XP
0/6 exercises

Imagine you have a spreadsheet with 10,000 rows of sales data. You could stare at those numbers for hours, or you could turn them into a chart and spot the trend in three seconds. That's the power of data visualization.

Matplotlib is Python's most popular plotting library. It's been around since 2003, and virtually every data science chart you've seen in Python was made with it (or a library built on top of it). In this tutorial, you'll learn how to create line charts, bar charts, scatter plots, and more.

How Do You Create a Basic Line Chart?

A line chart connects data points with straight lines. It's perfect for showing how something changes over time — stock prices, temperatures, website visitors.

In matplotlib, you give it two lists: one for the x-axis (horizontal) and one for the y-axis (vertical). Each pair of values becomes a point, and matplotlib draws lines between them.

Creating a basic line chart
Loading editor...

Notice we used fig, ax = plt.subplots(). This is the recommended way to create plots in matplotlib. fig is the whole figure (like a canvas), and ax is the axes (the actual chart area where data gets drawn).

When Should You Use a Bar Chart?

Bar charts are ideal for comparing categories. How did each product sell? Which city has the most population? Whenever you're comparing distinct groups, a bar chart is your best bet.

Creating a bar chart with custom colors
Loading editor...

You can also create horizontal bar charts using ax.barh(). These work great when your category labels are long — they're easier to read horizontally.

Horizontal bar chart
Loading editor...

How Do Scatter Plots Reveal Relationships?

Scatter plots show how two variables relate to each other. Each dot represents one data point, positioned by its x and y values. If the dots trend upward, there's a positive correlation. If they trend downward, it's negative. If they're scattered randomly, there's no clear relationship.

Think of a scatter plot like a map. Each dot is a person, and their position tells you two things about them simultaneously — like hours studied vs. exam score.

Scatter plot showing correlation
Loading editor...

How Do You Customize Colors, Markers, and Styles?

A chart without customization is like a report without formatting — it works, but nobody wants to read it. Matplotlib gives you full control over colors, line styles, markers, and fonts.

Customized line chart with legend and grid
Loading editor...

Here's a quick reference for common line styles and markers:

Quick reference for styles and markers
Loading editor...

What's the Difference Between Figure and Axes?

Understanding the relationship between Figure and Axes is the key to mastering matplotlib. Think of it like a picture frame and a photo:

  • Figure = the entire window or image. It's the frame that holds everything.
  • Axes = one individual chart inside the figure. A figure can contain multiple axes.
  • Axis = one side of the chart (x-axis, y-axis). Each axes object has two axis objects.
  • Figure vs axes
    Loading editor...

    How Do You Save Charts to Files?

    In a real project, you'll want to save your charts as image files to include in reports, presentations, or web pages. Matplotlib supports PNG, PDF, SVG, and more.

    Saving charts to files
    Loading editor...

    Practice Exercises

    Build a Temperature Line Chart
    Write Code

    Create a line chart showing daily temperatures. Use matplotlib.use('Agg') first, then create a figure with plt.subplots(). Plot the temperatures list against the days list. Set the title to 'Daily Temperatures', the x-label to 'Day', and the y-label to 'Temperature (F)'. Finally, print the title using ax.get_title().

    Loading editor...
    Build a Fruit Sales Bar Chart
    Write Code

    Create a bar chart showing fruit sales. Plot fruits on the x-axis and sales on the y-axis using ax.bar(). Set the title to 'Fruit Sales'. Print the number of bars using len(ax.patches) and print the height of the tallest bar.

    Loading editor...
    Create a Height vs Weight Scatter Plot
    Write Code

    Create a scatter plot of height vs weight data. Use ax.scatter() with alpha=0.6. Set the title to 'Height vs Weight'. Print the number of data points in the scatter collection using len(ax.collections[0].get_offsets()).

    Loading editor...
    Predict the Figure Properties
    Predict Output

    What will this code print? Think about figure dimensions and line count.

    Loading editor...
    Fix the Broken Legend
    Fix the Bug

    This code tries to create a chart with a legend, but the legend shows no entries. Fix the bug so the legend displays ['Revenue', 'Expenses'].

    Loading editor...
    Prepare Data for a Multi-Series Chart
    Write Code

    You have quarterly revenue data for three products. Create a grouped bar chart by computing the x-positions for each group. Given quarters (4 items) and bar width 0.25, calculate x positions for three product groups so bars sit side by side. Print the x positions for each product as lists (use list() to convert numpy arrays). Product A should be at positions [0, 1, 2, 3], Product B at [0.25, 1.25, 2.25, 3.25], and Product C at [0.5, 1.5, 2.5, 3.5].

    Loading editor...