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 chart | Matplotlib call | When it's the wrong choice |
|---|---|---|---|
| Discrete categories to compare (sales by person, votes by option) | Bar chart | plt.bar() | More than ~25 bars — switch to a horizontal bar or table |
| A value changing over an ordered axis (revenue by month) | Line chart | plt.plot() | Categories with no natural order — connecting them implies a false trend |
| Two measured variables per item (height vs. weight) | Scatter plot | plt.scatter() | One variable is a category, not a number |
| Parts of a single whole that sum to 100% | Pie chart | plt.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 comparison | plt.bar() | Only reach for pie/line/scatter when the data genuinely demands it |
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.
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()
Array-Based Method (Recommended)
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.
| Symptom | Likely cause | Fix |
|---|---|---|
plt.show() opens a blank window or errors on a server | No 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 image | Tight default bounding box crops them | Add bbox_inches="tight" to savefig, or call plt.tight_layout() |
| Long category names overlap on the x-axis | Labels too wide for the spacing | plt.xticks(rotation=45, ha="right") |
| Second chart draws on top of the first | Figure was never cleared | Call plt.figure() before each chart, or plt.clf() between them |
| Colors look identical between slices/bars | Relying on defaults with too many categories | Pass an explicit color=[...] list or use a colormap |
ModuleNotFoundError: No module named 'matplotlib' | Installed to a different Python/venv | Reinstall 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.