Analytics

Python Data Visualization with Matplotlib: Complete Tutorial

Master the essential chart types in Python: bar charts, line charts, scatter plots, and pie charts with step-by-step examples and code samples.

By InventiveHQ Team

Matplotlib is Python's foundational plotting library, and four chart types cover the vast majority of everyday data visualization: bar charts for comparing categories, line charts for trends over time, scatter plots for the relationship between two variables, and pie charts for share of a whole. Every chart follows the same five-step rhythm: import matplotlib.pyplot as plt, prepare your data as plain Python lists or NumPy arrays, call a plotting function (plt.bar, plt.plot, plt.scatter, or plt.pie), decorate it with labels and a title, then render with plt.show() or save with plt.savefig().

That is the summary an AI overview would hand you. What it can't show you is which chart fits your data, the exact five-step flow every plot shares, or the failure modes that make plt.show() open a blank window on a server. The diagrams, decision table, and troubleshooting section below make those concrete.

Which Chart Should You Use?

Picking the wrong chart type is the most common visualization mistake — a pie chart with twelve slices, or a line chart connecting unordered categories. Match your data's shape to the chart before you write any code.

Your data looks like…Use this chartMatplotlib callWhen it's the wrong choice
Discrete categories to compare (sales by person, votes by option)Bar chartplt.bar()More than ~25 bars — switch to a horizontal bar or table
A value changing over an ordered axis (revenue by month)Line chartplt.plot()Categories with no natural order — connecting them implies a false trend
Two measured variables per item (height vs. weight)Scatter plotplt.scatter()One variable is a category, not a number
Parts of a single whole that sum to 100%Pie chartplt.pie()More than ~5 slices, or values you want compared precisely
Which should I pick first?Bar chart — it is the most accurately read and works for almost any comparisonplt.bar()Only reach for pie/line/scatter when the data genuinely demands it
Decision flow for choosing a Matplotlib chart type A flow that routes from the question "what does your data show?" to bar, line, scatter, or pie charts, with each option highlighting in turn. What does your data show? Bar chart Compare discrete categories — plt.bar() Line chart Trend over an ordered axis — plt.plot() Scatter plot Relationship between two variables — plt.scatter() Pie chart Parts of a whole, ≤5 slices — plt.pie()

The Five-Step Matplotlib Workflow

Every chart in this tutorial — and nearly every Matplotlib figure you will ever write — follows the same five steps. Learn the rhythm once and every chart type becomes a variation on it.

The five-step Matplotlib plotting workflow Import, prepare data, plot, decorate, and render, shown as five connected cards with a token moving along the path. Every Matplotlib chart, in five steps 1. Import import matplotlib .pyplot as plt 2. Data lists or NumPy arrays 3. Plot plt.bar / plot scatter / pie 4. Decorate title, labels, xticks, legend 5. Render plt.show() or plt.savefig()
Advertisement

Prerequisites and Setup

Before diving into chart creation, ensure you have the required Python libraries installed. These two packages provide all the functionality needed for data visualization and numerical operations.

pip3 install matplotlib
pip3 install numpy

Creating Bar Charts for Data Comparison

Bar charts excel at comparing discrete categories or values. They're perfect for visualizing survey results, sales figures, or any data where you want to compare quantities across different groups. In this example, we'll create a simple comparison of weekly walking distances.

import matplotlib.pyplot as plt

# Create a list showing how many miles each person walked
values = [1, 2, 3]

# Create a list of names
names = ["Matt", "Sally", "John"]

# Declare bar chart
plt.bar(values, values)

# Associate the names with the values
plt.xticks(values, names)

# Show the bar chart
plt.show()

The code above creates a simple bar chart comparing walking distances. The plt.bar() function creates the bars, while plt.xticks() labels each bar with the corresponding person's name.

Line Charts for Trend Analysis

Line charts are ideal for displaying data changes over time or showing relationships between continuous variables. They help identify trends, patterns, and correlations in your data. The connected points create a visual flow that makes trends immediately apparent.

import matplotlib.pyplot as plt

# Declare line chart and pass in Y values for line
plt.plot([1, 23, 2, 4])

# Declare the X values for the chart and assign labels to each point
plt.xticks([0, 1, 2, 3], ["one", "two", "three", "four"])

# Assign a label to show on the left side of the chart
plt.ylabel('some numbers')

# Draw the chart
plt.show()

This example demonstrates how plt.plot() creates a line connecting data points. The plt.ylabel() function adds a descriptive label to the y-axis, making the chart more informative.

Scatter Plots for Relationship Discovery

Scatter plots are powerful tools for exploring relationships between two variables. They help identify correlations, clusters, outliers, and patterns that might not be obvious in raw data. Each point represents a pair of values, making it easy to spot trends.

Individual Point Method

import matplotlib.pyplot as plt

# Draw individual points on the chart
plt.scatter(1, 2)
plt.scatter(2, 3)
plt.scatter(3, 5)
plt.scatter(4, 3)

# Show the scatterplot
plt.show()

For efficiency and cleaner code, it's better to pass arrays of coordinates to the scatter plot function:

import matplotlib.pyplot as plt

# Declare arrays showing the X and Y coordinates
x = [1, 2, 3, 4, 5, 6, 7]
y = [1, 3, 3, 2, 5, 7, 9]

# Pass all the points into the scatter plot
plt.scatter(x, y)

# Show the scatterplot on the screen
plt.show()

Adding Trend Lines to Scatter Plots

When scatter plot points show a pattern, adding a trend line helps visualize the relationship more clearly. NumPy provides powerful functions for calculating linear regression and creating best-fit lines through your data points.

💡 Pro Tip: NumPy's polyfit() function calculates the best-fit line coefficients, while poly1d() creates a polynomial function for generating trend line coordinates.

import matplotlib.pyplot as plt
import numpy as np

# Declare arrays showing the X and Y coordinates
x = [1, 2, 3, 4, 5, 6, 7]
y = [1, 3, 3, 2, 5, 7, 9]

# Create scatter plot
plt.scatter(x, y)

# Calculate trend line coefficients
m, b = np.polyfit(x, y, 1)

# Create trend line
plt.plot(x, [m*i + b for i in x], color='red', linestyle='--', linewidth=2)

# Add labels
plt.xlabel('X Values')
plt.ylabel('Y Values')
plt.title('Scatter Plot with Trend Line')

# Show the plot
plt.show()

# Print the correlation strength
print(f"Slope: {m:.2f}, Intercept: {b:.2f}")

This enhanced version adds a red dashed trend line that clearly shows the data's upward trend. The slope and intercept values help quantify the relationship strength.

Pie Charts for Proportional Data

Pie charts effectively show how individual parts contribute to a whole. They're perfect for displaying percentages, market share, budget allocation, or any data where the total equals 100%. Each slice represents a proportion of the complete dataset.

Basic Pie Chart

import matplotlib.pyplot as plt

# Create list of values
values = [1, 2, 3]

# Create a list of names
names = ["Matt", "Sally", "John"]

# Declare pie chart
plt.pie(values, labels=names)

# Show pie chart
plt.show()

The basic pie chart automatically calculates proportions and assigns different colors to each slice. Labels are positioned around the chart for easy identification.

Exploded Pie Chart for Emphasis

To highlight specific data segments, you can "explode" slices by pulling them away from the center. This technique draws attention to important categories or outliers in your data.

# Exploded pie chart
import matplotlib.pyplot as plt

# Create list of values
values = [1, 2, 3]

# Create a list of names
names = ["Matt", "Sally", "John"]

# Define explosion distances (0 = no explosion, 0.1 = slight separation)
explode = (0, 0.1, 0)

# Create exploded pie chart
plt.pie(values, explode=explode, labels=names, autopct='%1.1f%%')

# Show pie chart
plt.show()

The exploded version separates Sally's slice from the main chart, creating visual emphasis. The autopct parameter adds percentage labels to each slice.

Loading Real Data Instead of Hard-Coded Lists

The examples above use inline lists so you can focus on the plotting API, but real charts read from files. The most common source is a CSV, and pandas turns a two-column file into chart-ready data in one line:

import pandas as pd
import matplotlib.pyplot as plt

# data.csv has columns: name,miles
df = pd.read_csv("data.csv")

plt.bar(df["name"], df["miles"])
plt.title("Weekly Walking Distance")
plt.savefig("walking.png", dpi=150, bbox_inches="tight")

Because Matplotlib works with any sequence of numbers, the same call accepts JSON parsed into a list, rows from a database cursor, or a NumPy array — the plotting code never changes, only how you load the data.

Common Matplotlib Problems and Fixes

Most first-time Matplotlib frustration comes from a handful of recurring issues. Match your symptom to the fix below.

SymptomLikely causeFix
plt.show() opens a blank window or errors on a serverNo GUI backend available (headless/SSH)Save instead: plt.savefig("chart.png"), or set matplotlib.use("TkAgg") before importing pyplot
Axis labels or title are cut off in the saved imageTight default bounding box crops themAdd bbox_inches="tight" to savefig, or call plt.tight_layout()
Long category names overlap on the x-axisLabels too wide for the spacingplt.xticks(rotation=45, ha="right")
Second chart draws on top of the firstFigure was never clearedCall plt.figure() before each chart, or plt.clf() between them
Colors look identical between slices/barsRelying on defaults with too many categoriesPass an explicit color=[...] list or use a colormap
ModuleNotFoundError: No module named 'matplotlib'Installed to a different Python/venvReinstall in the active environment: python3 -m pip install matplotlib

Key Takeaways and Next Steps

You now have the fundamental skills to create four essential chart types using Python and Matplotlib:

  • Bar charts for comparing discrete categories and values

  • Line charts for showing trends and changes over time

  • Scatter plots for exploring relationships between variables

  • Pie charts for displaying proportional data and percentages

These visualization techniques form the foundation for more advanced data analysis and presentation. As you continue developing your Python skills, consider exploring Python functions and project management with requirements.txt to build more sophisticated data visualization applications.

Frequently Asked Questions

How do I install Matplotlib in Python?

Run pip3 install matplotlib from your terminal. Add pip3 install numpy if you plan to calculate trend lines or generate synthetic data, since NumPy powers Matplotlib's numerical helpers. On a fresh machine you may also need pip3 install --upgrade pip first. Verify the install with python3 -c "import matplotlib; print(matplotlib.__version__)".

What is the difference between plt.plot() and plt.scatter()?

plt.plot() draws a connected line through your points, so it implies an ordered relationship (usually time or a continuous X axis). plt.scatter() draws unconnected markers, so it shows the relationship between two independent variables without implying order. Use plot for trends over time and scatter for correlation between two measurements.

Why does plt.show() open a blank or non-interactive window?

plt.show() needs a GUI backend. On a headless server, over SSH, or inside some IDEs the default backend cannot open a window, so you see nothing or an error. Either set an interactive backend (matplotlib.use("TkAgg")) or, more commonly, save to a file instead with plt.savefig("chart.png", dpi=150, bbox_inches="tight"), which needs no display at all.

How do I add a trend line to a Matplotlib scatter plot?

Use NumPy's polyfit to compute the slope and intercept of the best-fit line, then plot that line over your scatter: m, b = np.polyfit(x, y, 1) followed by plt.plot(x, [m*i + b for i in x]). The 1 requests a first-degree (straight) fit. For the sample data in this tutorial the slope is about 1.21 and the intercept about -0.57.

When should I use a bar chart versus a pie chart?

Use a bar chart when you want people to compare exact values across categories, which is nearly always. Use a pie chart only when there are a handful of slices (roughly two to five) that add up to a meaningful whole and the story is "share of total." Humans read bar lengths far more accurately than pie angles, so bar charts are the safer default for more than five categories.

How do I save a Matplotlib chart as a PNG instead of showing it?

Replace plt.show() with plt.savefig("chart.png", dpi=150, bbox_inches="tight"). Call it before plt.show() if you want both, because show() clears the figure. Use dpi=300 for print quality and change the extension to .svg or .pdf for vector output that scales without blurring.

Why do my axis labels get cut off when I save the figure?

The default bounding box crops tight to the axes, clipping rotated tick labels and titles. Add bbox_inches="tight" to savefig, or call plt.tight_layout() before saving. For long category names, rotate them with plt.xticks(rotation=45, ha="right") so they do not overlap.

Can Matplotlib read data directly from a CSV file?

Matplotlib itself does not parse CSV, but it pairs naturally with the standard-library csv module or with pandas. A common pattern is import pandas as pd; df = pd.read_csv("data.csv") then plt.bar(df["name"], df["value"]). Pandas handles the parsing and type inference, and Matplotlib draws the result.

Advertisement