A Beginner‘s Guide to Matplotlib: Python Data Visualization Essentials
Data visualization is an essential skill for data scientists and machine learning practitioners. Visualizing your data helps reveal patterns, trends and outliers, and makes your findings easier to communicate to others. When it comes to data visualization in Python, the go-to library is Matplotlib.
Matplotlib is a powerful and flexible plotting package that lets you create production-quality charts, graphs and figures with just a few lines of Python code. It integrates tightly with the Python data science stack and is an indispensable tool for doing exploratory data analysis and presenting data.
In this beginner‘s guide, we‘ll introduce the core matplotlib plotting APIs and show you how to use them to create common statistical plots like line charts, bar charts, histograms, scatter plots and more. By the end, you‘ll know how to choose the right plot type for your data and customize visualizations to make them clear and informative.
Let‘s dive in and learn the essentials of data visualization with Matplotlib!
Overview of Core Matplotlib Plot Types
Matplotlib provides a range of different chart types suitable for plotting different kinds of data. Here are some of the most commonly used plots you‘ll encounter:
- Line plots – for tracking changes in a variable over time
- Scatter plots – for visualizing relationships between two continuous variables
- Bar charts – for comparing categorical data
- Histograms – for exploring the distribution of a single variable
- Box plots – for comparing distributions between groups
- Pie charts – for showing parts of a whole
We‘ll go through each of these plot types in the sections below. But first, let‘s import the libraries we need and load in a sample dataset to work with:
import matplotlib.pyplot as plt import numpy as np import pandas as pd%matplotlib inline plt.style.use(‘ggplot‘)
df = pd.read_csv(‘movies.csv‘)
Here we import matplotlib‘s pyplot interface as plt, which provides a MATLAB-like way of creating plots. We also import numpy for working with arrays and pandas for loading and manipulating our movie dataset. The %matplotlib inline magic lets us display plots inside the Jupyter notebook.
With the setup out of the way, let‘s see how to create each type of plot.
Line Plots
Line plots are useful for showing trends over time. To create one in matplotlib, we use the plt.plot function.
fig, ax = plt.subplots(figsize=(8, 4)) ax.plot(df[‘release_year‘], df[‘revenue_millions‘]) ax.set_xlabel(‘Release Year‘) ax.set_ylabel(‘Revenue (millions)‘) ax.set_title(‘Movie Revenue by Year‘)

Here‘s a breakdown of what this code does:
- Create a new figure and axis with plt.subplots. Specify the figure size in inches.
- Plot revenue vs release year using ax.plot. Matplotlib will automatically draw a line connecting the data points.
- Add labels for the x and y axis using ax.set_xlabel and ax.set_ylabel.
- Set a title for the plot with ax.set_title.
There are many other ways you can customize the appearance of a matplotlib plot. For example, you can change the line color and style, add a legend, adjust the axis limits and more. Check the matplotlib documentation for the full set of options.
Scatter Plots
Scatter plots are a good choice for visualizing relationships between two variables. They allow us to see if there‘s any correlation between the variables or to identify any outliers.
To create a scatter plot, we use the ax.scatter method:
fig, ax = plt.subplots(figsize=(6, 6)) ax.scatter(df[‘runtime‘], df[‘revenue_millions‘]) ax.set_xlabel(‘Runtime (minutes)‘) ax.set_ylabel(‘Revenue (millions)‘) ax.set_title(‘Relationship between movie runtime and revenue‘)

To draw a scatter plot:
- Create a figure and axis
- Plot the data points using ax.scatter, passing in the x and y variables
- Add labels and a title
We can see from this plot that there‘s a slight positive correlation between a movie‘s runtime and its revenue – longer movies tend to make more money, up to a point. There are a few outliers with runtimes over 3 hours that don‘t follow this trend.
Bar Charts
Bar charts are useful for comparing values across different categories. A common use case in data analysis is comparing summary statistics like means or medians between groups.
Here‘s an example that compares the median movie runtime for each genre:
genres = df[‘genre‘].unique() medians = df.groupby(‘genre‘)[‘runtime‘].median()fig, ax = plt.subplots(figsize=(8, 4)) ax.bar(genres, medians) ax.set_xlabel(‘Genre‘) ax.set_ylabel(‘Median runtime (minutes)‘)
ax.set_title(‘Median movie runtime by genre‘) plt.xticks(rotation=45)

The steps to create a bar chart are:
- Get the category labels (genres) and summary statistic to plot (median runtime)
- Create a figure and axis
- Plot the bars with ax.bar, passing in the labels and heights
- Set labels and a title
- Rotate the x-tick labels so they don‘t overlap
Action and Adventure movies have the longest median runtimes, while Documentaries and Dramas are on the shorter side.
Histograms
Histograms let us explore how a continuous variable is distributed. They work by dividing the variable range into bins and counting how many data points fall into each bin.
fig, ax = plt.subplots(figsize=(8, 4)) ax.hist(df[‘rating‘], bins=20) ax.set_xlabel(‘Rating‘) ax.set_ylabel(‘Frequency‘) ax.set_title(‘Distribution of movie ratings‘)

Creating a histogram in matplotlib is straightforward:
- Create a figure and axis
- Call ax.hist and pass in the variable to plot. Optionally specify the number of bins to use.
- Add labels and a title
The histogram shows that this dataset contains mostly highly rated movies, with a median rating over 7. Ratings are clustered in the 6-8 range.
Box plots
Box plots (also known as box-and-whisker plots) provide a concise summary of how values are distributed within a group. They show the median, interquartile range and outliers.
Box plots are especially handy for comparing distributions between multiple groups:
fig, ax = plt.subplots(figsize=(8, 4)) df.boxplot(column=‘runtime‘, by=‘genre‘, ax=ax) ax.set_xlabel(‘Genre‘) ax.set_ylabel(‘Runtime (minutes)‘) ax.set_title(‘Movie runtime by genre‘) plt.suptitle(‘‘) plt.xticks(rotation=45)

Here‘s how we created these box plots comparing movie runtimes across genres:
- Create a figure and axis
- Call the pandas df.boxplot method, specifying the variable to plot and the grouping variable. Pass in the axis to draw on.
- Add labels and a title. Set an empty suptitle to remove the extra text pandas adds
- Rotate the x-tick labels
The box plots reveal some interesting patterns. Documentaries and Dramas have lower runtimes overall, while Action and Adventure movies skew longer. Each genre has some outliers on the high end.
Pie Charts
Pie charts are used to show parts of a whole. They work best when there are a limited number of categories and each takes up a sizable fraction of the whole.
Here‘s how to create a pie chart showing the breakdown of movies by genre:
genre_counts = df[‘genre‘].value_counts()fig, ax = plt.subplots(figsize=(6, 6)) ax.pie(genre_counts, labels=genre_counts.index, autopct=‘%1.1f%%‘) ax.set_title(‘Percentage of movies by genre‘)

To draw a pie chart in matplotlib:
- Get the category counts
- Create a figure and axis
- Call ax.pie, passing in the counts and labels. Use autopct to display the category percentages.
- Add a title
The pie chart shows that over half the movies in this dataset are either Action or Drama. Documentaries make up the smallest slice.
Data Visualization Best Practices
We‘ve covered all the major chart types you‘ll use when visualizing data with matplotlib. To finish off, here are some general tips for creating effective data visualizations:
Choose the right plot for the data and question at hand. For example, don‘t use a pie chart to compare means between 20 categories.
Keep charts clean, simple and easy to interpret. Avoid clutter and only include necessary information.
Use informative labels and titles so the plot can be understood without too much extra context.
Make text legible. Use big enough font sizes and avoid rotated text.
Use color sparingly. Avoid using too many different colors or colors that are hard to distinguish.
Conclusion
We‘ve reached the end of our tour of the matplotlib visualization library. Hopefully you now feel comfortable creating common chart types like line plots, bar charts, histograms, scatter plots and pie charts in Python.
The key to mastering data visualization is practice. The more time you spend exploring datasets and trying out different visual representations, the better you‘ll get at creating clear and meaningful visualizations. Have fun putting your new matplotlib skills into practice!
As you continue your data science journey, data visualization will be an indispensable tool. Not only is visualization important for exploring and gaining insights from data, it‘s a key communication tool. Great visualizations let you share your findings with colleagues and stakeholders in an engaging and accessible way.
To learn more about matplotlib and data visualization in Python, check out the official documentation as well as the many great tutorials and examples available online. There‘s enough to keep you busy for a long time.
Happy visualizing!