Matplotlib Cheat Sheet. Basic plots, include code samples. | by XuanKhanh Nguyen | Towards Data Science

Matplotlib is a plotting library for the Python programming language. The most used module of Matplotib is Pyplot which provides an interface like Matlab but instead, it uses Python and it is open source.
In this note, we will focus on basic Matplotlib to help visualize our data. This is not a comprehensive list but contains common types of data visualization formats. Let’s hop to it!
The structure of this note:
Anatomy of Matplotlib FigureStart with PyplotChart Types
Anatomy of Matplotlib Figure
Start with Pyplot
Chart Types
A figure contains the overall window where plotting happens.
Axes: It is what we generally think of as a plot. Each Axes has a title, an x-label, and a y-label.
Note: We can have more than one Axes in a figure which helps in building multiple plots.
Axis are the number line like objects and help to generate the graph limits. Every axes has an x-axis and y-axis for plotting.
Ticks are the markers denoting data points on axes, that is, the values used to show specific points on the coordinate axis. These values can be a number or a string. Whenever we plot a graph, the axes adjust and take the default ticks. Matplotlib’s default ticks are generally sufficient in common situations but are in no way optimal for every plot.
A spine to a graph is the edge of the graph. It connects the axis tick marks and noting the boundaries of the data area.
Pyplot is a module of Matplotlib which provides simple functions to add plot elements like lines, images, text, etc. to the current axes in the current figure.
At first, we set up the notebook for plotting and importing the packages we will use:
import numpy as npimport matplotlib.pyplot as pltplt.style.use('seaborn-whitegrid') # Set the aesthetic style of the plots
A figure and axes can be created as follows:
fig, ax = plt.subplots()print(type(fig))print(type(ax))
We commonly use the variable name fig to refer to a figure instance, and ax to refer to an axes instance or group of axes instances.
Once we have created an axes, we can use the plt.plot function to plot some data. Let’s start with a simple plot. Perhaps the simplest of all plots is the visualization of a single function y = 2x.
fig, ax = plt.subplots()x = np.random.randint(1,10, size=10)y = 2*x plt.plot(x,y) # same as ax.plot(x,y)plt.show()
If we want to create a single figure with multiple lines, we can simply call the plot function multiple times:
# Multiple linesfig, ax = plt.subplots()x = np.random.randint(1,10, size=10)y = 2*x plt.plot(x,y)plt.plot(x,x+3)plt.show()
The plt.plot() function takes additional arguments that can be used to specify the line color and style. To adjust, we can use the color linestyle keyword, which accepts a string argument representing virtually any imaginable color/style. Colors and styles can be specified in a variety of ways:
fig, ax = plt.subplots()x = np.linspace(0,10,1000)y = 2*x# set of default color and styleplt.plot(x, np.cos(x))# RGB tuple, values 0 to 1, solid styleplt.plot(x, np.sin(x), color=(1.0,0.2,0.3),linestyle='-')# specify color by name, dashed styleplt.plot(x, y, color='blue', linestyle='--')# short color code (rgbcmyk), dotted style   plt.plot(x, x+3, color='g',linestyle=':')# Grayscale between 0 and 1, dashdot style    plt.plot(x, np.log(x), color='0.75',linestyle='-.')# Hex code (RRGGBB from 00 to FF), dashed style  plt.plot(x, x, color='#FFDD44',linestyle='--')
Matplotlib does a decent job of choosing default axes limits for our plot, but sometimes it’s nice to have finer control. The most basic way to adjust axis limits is to use the plt.xlim() and plt.ylim() methods:
plt.xlim(0, 11)plt.ylim(-1.5, 10)
As the last piece of this section, we will briefly look at the labeling of plots: titles, axis labels, and simple legends.
plt.plot(x, np.sin(x), label='y=sin(x)')plt.plot(x,np.cos(x), label='y=cos(x)')plt.title('Sine and Cosine Functions ')plt.xlabel("x-axis")plt.ylabel("y-axis")plt.legend() # Describing the element of the graphplt.show()
There are various plots which can be created using python Matplotlib. We will discuss the most used plots for data visualization in this section.
We use the World Happiness Report dataset from Kaggle. I cleaned the data and combined all files in happiness_rank.csv file. You can download and clean the data or just simply download the final result here. I recommend you check out my data cleaning codes on Github.
A scatter plot is a type of chart that is often used in statistics and data science. It consists of multiple data points plotted across two axes. Each variable depicted in a scatter plot would have multiple observations. This can be a very useful chart type whenever we would like to see if there is any relationship between two sets of data.
We use a scatter plot to identify the relationship of the data with each variable (i.e, correlation, or trend patterns.) It also helps in detecting outliers in the plot.
In machine learning, scatter plots are often used in regression, where x and y are continuous variables. They are also used in clustering scatters or outlier detection.
Scatter plots are not suitable if we are interested in observing time patterns.
A scatter plot is used with numerical data or numbers. So, if we have categories such as three divisions, five products, etc, a scatter plot would not reveal much.
fig, ax = plt.subplots(figsize = (12,6))x = df['GDP']y = df['Score']plt.scatter(x,y)plt.title('GDP vs Happiness Score')plt.xlabel('GDP')plt.ylabel('Score')
3D Scatterplot
3D Scatterplot helps in visualizing three numerical variables in a three- dimensional plot.
from mpl_toolkits.mplot3d import Axes3Dfig = plt.figure(figsize=(10,6))ax = fig.add_subplot(111, projection='3d')ax.scatter(df['Year'],df['GDP'],df['Score'], s=30)ax.set( xlabel='Year', ylabel='GDP',zlabel='Score')plt.xticks(np.arange(2015,2020,step =1))plt.show()
Scatter plot with a linear regression line of best fit
We will implement linear regression with Scikit-learn using the LinearRegression. After creating a linear regression object, we can obtain the line that best fits our data by calling the fit method.
x = df['GDP'].values.reshape(-1,1).astype('float32')y = df['Score'].values.reshape(-1,1).astype('float32')# Split the data to train and test dataX_train, X_test, y_train, y_test = train_test_split(x, y, test_size=0.2, random_state=0)# Apply Linear Regression Algorithmsh = LinearRegression()  h.fit(X_train,y_train)y_pred = h.predict(X_test)fig,(ax1) = plt.subplots(1, figsize = (12,6))ax1.scatter (X_test, y_test, s = 8)plt.plot(X_test,y_pred, color = 'black', linewidth = 2)plt.show()
A diverging bar chart is a bar chart that has the marks for some dimension members pointing up or right, and the marks for other dimension members pointing in the opposite direction (down or left, respectively).
Note:
The marks flowing down or left does not necessarily represent negative values.
The divergent line can represent zero, but it can also be used to simply separate the marks for two-dimension members.
We use diverging bars to see how the items are varying based on a single metric and visualize the order and amount of this variance. If our primary objective is to compare the trend of each dimension member, a divergent bar chart is a good option.
The drawback to using diverging bar charts is that it’s not as easy to compare the values across dimension members as it is with a grouped bar chart.
We only use 2019 data as an example.
# Data processingtop_economies = ['United States', 'China','Japan', 'Germany','United Kingdom','India', 'France','Brazil', 'Canada']df_top = df_19[(df_19['Country'].isin(top_economies))].sort_values(['Country'])df_top.reset_index(drop=True)x = df_top.loc[:, ['Score']]df_top['Score_z'] = (x - x.mean())/x.std()df_top['colors'] = ['red' if x < 0 else 'blue' for x in df_top['Score_z']]df_top.sort_values('Score_z', inplace=True)df_top.reset_index(inplace=True)# Draw plotplt.figure(figsize=(8,6), dpi= 50)plt.hlines(y=df_top.index, xmin=0, xmax=df_top.Score_z, color=df_top.colors, alpha=0.5, linewidth=20)# Decorationsplt.gca().set(ylabel='Country', xlabel='Happiness_Score')plt.yticks(df_top.index, df_top.Country, fontsize=15)plt.title('Happiness Score for Top Economies in 2019', fontdict={'size':20})plt.grid(linestyle='--', alpha=0.5)plt.show()
The idea of an area chart is based on the line chart. Colored regions (areas) show us the development of each variable over time.
There are three types of area charts: regular area chart, stacked area chart, and 100% stacked area chart.
We use area charts to show how the parts of a complete change over time. For example, the happiness score has six generating divisions; we would like to see each of these divisions’ contributions.
Moreover, if we are interested in the portion generated by each division and not that much of the total amount of the division self, we can use a 100% stacked area chart. This will show each division’s percentage contribution over time.
Area charts are not the best choice if we want to compare the size of different shares with each other. If you want to show that one share overtook another one; or if the differences between our values are very small, consider a line chart instead.
Python Implementation
# Regular Area Chart# Create datax = df_top['Score']y = df_top['GDP']# Change the color and its transparencyplt.fill_between( x, y, color="skyblue", alpha=0.2)plt.xlabel('Score')plt.ylabel('GDP')plt.plot(x, y, color="Slateblue", alpha=0.6)
# Stacked Area Chartplt.stackplot(df_top.index,              [df_top['GDP'], df_top['Health'],               df_top['Support'], df_top['Freedom']],              df_top['Generosity'], df_top['Corruption'],              labels=['GDP', 'Health', 'Support', 'Freedom','Generosity','Corruption'],              alpha=0.8)plt.legend(loc=2, fontsize='large')plt.show()
# 100% Stacked Area Chartdata_perc = df_top[['GDP', 'Health', 'Support', 'Freedom','Generosity','Corruption']]data_perc = data_perc.divide(data_perc.sum(axis=1), axis=0)plt.stackplot(data_perc.index,              [data_perc['GDP'], data_perc['Health'],               data_perc['Support'], data_perc['Freedom']],              data_perc['Generosity'], data_perc['Corruption'],              labels=['GDP', 'Health', 'Support', 'Freedom','Generosity','Corruption'],              alpha=0.8)plt.legend(loc=2, fontsize='large')plt.show()
Bar charts are among the most frequently used chart types. As the name suggests, a bar chart is composed of a series of bars illustrating a variable’s development.
There are four types of bar charts: regular bar chart, horizontal bar chart, group bar chart, and stacked bar chart.
Bar charts are great when we want to track the development of one or two variables over time. One axis of the chart shows the specific categories being compared, and the other axis represents a measured value.
A simple bar chart isn’t suitable when we have a single period breakdown of a variable. For example, if I want to portray the main business lines that contributed to a company’s revenues, I wouldn’t use a bar chart. Instead, I would create a pie chart or one of its variations.
# Bar Chartcountries = ['United States','Japan', 'Germany','Brazil', 'India']y_pos = np.arange(len(countries))data = df_19[(df_19['Country'].isin(countries))].sort_values(['Country'])data.sort_values('GDP', inplace=True)data.reset_index(drop=True)plt.bar(y_pos, data['GDP'], align='center', alpha=0.5)plt.xticks(y_pos, data['Country'])plt.ylabel('GDP')plt.title('Bar Chart')plt.show()
# Horizontal bar chartdf_19[(df_19['Country'].isin(countries))].sort_values(['Country'])data.sort_values('Score', inplace=True)data.reset_index(drop=True)plt.barh(y_pos, data['Score'], align='center', alpha=0.5)plt.yticks(y_pos, data['Country'])plt.xlabel('Score')plt.title('Horizontal Bar Chart')plt.show()
# Group bar chartindex = np.arange(5)width = 0.35fig, ax = plt.subplots(figsize=(9, 6))rects1 = ax.bar(index - width / 2, data['GDP'],                width, color='#1f77b4', alpha=0.5)rects2 = ax.bar(index + width / 2, data['Health'],                width, color='#1f77b4')plt.xticks(index, gdp['Country'])plt.legend((rects1[0], rects2[0]), ('GDP', 'Health'))plt.show()
# Stacked bar chartfig = plt.figure(figsize=(14,10))rect1 = plt.bar(np.arange(5), data['Support'],                width=0.5, color='lightblue')rect2 = plt.bar(np.arange(5), data['Freedom'],                width=0.5, color='#1f77b4')plt.xticks(index, data['Country'])plt.legend((rect1[0], rect2[0]), ('Support', 'Freedom'))plt.show()
Lollipop chart serves a similar purpose as an ordered bar chart in a visually pleasing way. We use lollipop charts to show the relationship between a numerical variable and another numerical or categorical variable.
The lollipop chart is often claimed to be useful compared to a normal bar chart, if we are dealing with a large number of values and when the values are all high, such as in the 80–90% range (out of 100%). Then a large set of tall columns can be visually aggressive.
If our data has unsorted bars of very similar length — it is harder to compare the lengths of two very similar lollipops than standard bars.
Python Implementation
(markerline, stemlines, baseline) = plt.stem(data['Country'],                                             data['GDP'])plt.setp(markerline, marker='o', markersize=15,         markeredgewidth=2, color='lightblue')plt.setp(stemlines, color='lightblue')plt.setp(baseline, visible=False)plt.tick_params(labelsize=12)plt.ylabel('GDP', size=12)plt.ylim(bottom=0)plt.show()
A histogram is a vertical bar chart that depicts the distribution of a set of data. Histograms are used to show distributions of variables while bar charts are used to compare variables. Histograms plot quantitative data with ranges of the data grouped into bins or intervals while bar charts plot categorical data.
Note: Bar graphs have space between the columns, while histograms do not.
Histograms are great when we would like to show the distribution of the data we are working with. This allows us to group continuous data into bins and hence, provide a useful representation of where observations are concentrated.
Python Implementation
# Histogramfig = plt.figure(figsize=(8,6))plt.hist(df_19['Corruption'], bins=6, density=True)plt.grid(alpha=0.2)plt.show()
A box plot or whisker plot is a way of summarizing a set of data measured on an interval scale. This type of graph is used to show the shape of the distribution, its central value, and its variability.
We use box plots in explanatory data analysis, indicating whether a distribution is skewed and whether there are potential unusual observations (outliers) in the data set.
Box plots are also very useful when large numbers of observations are involved and when two or more data sets are being compared.
Box plots do not show the distribution in as much detail as a stem and leaf plot or histogram does.
Suppose we have a dataset containing the number of articles Medium members read in 2020’s first six months.
# Create datasetuser_1 = [10, 3, 15, 21, 17, 14]user_2 = [5, 13, 10, 7, 9, 12]data = [user_1, user_2]fig = plt.figure(figsize =(8, 6))   # Create axes instance ax = fig.add_axes([0, 0, 1, 1])   # Create plot bp = ax.boxplot(data)   # Show plot plt.xticks([1,2],['user_1','user_2'])plt.show()
Pie charts are a classic way to show the composition of groups. A pie chart is a circular graph divided into slices. The larger a slice is the bigger portion of the total quantity it represents.
However, it is not generally advisable to use nowadays because the area of the pie portions can sometimes become misleading. So, while using pie charts, it is highly recommended to explicitly write down the percentage or numbers for each portion of the pie.
Pie charts are best suited to depict sections of a whole.
We can’t use a pie chart in situations when we would like to show how one or more variables develop over time.
Suppose we have a dataset containing information about Medium members. We want to see the percentage of articles read in 2020’s first six months.
# Pie Chartfig = plt.figure(figsize=(8,8))labels = 'Jan', 'Feb', 'March', 'April', 'May', 'June'user_1 = [10, 3, 15, 21, 17, 14]p = plt.pie(user_1, labels=labels, explode=(0.07, 0, 0, 0, 0, 0),            autopct='%1.1f%%', startangle=130, shadow=True)plt.axis('equal')for i, (Jan, Feb, March, April, May, June) in enumerate(p):    if i > 0:        Jan.set_fontsize(12)        Feb.set_fontsize(12)        March.set_fontsize(12)        April.set_fontsize(12)        May.set_fontsize(12)        June.set_fontsize(12)plt.show()
A treemap chart is similar to a pie chart and it does better work without misleading the contributions of each group. Treemap chart allows us to split the sum of the whole into hierarchies and then show an internal breakdown of each of these hierarchies.
Treemaps are often used for sales data, as they capture relative sizes of data categories, allowing for a quick, high-level summary of the similarities and anomalies within one category as well as between multiple categories.
Treemap charts are not suitable when our data is not divisible into categories and sub-categories.
Moreover, when we’re encoding data with area and intensity of color, our eyes aren’t great a detecting relatively minor differences in either of these dimensions. If our data is such that our audience needs to make precise comparisons between categories, it’s even more cumbersome when the categories aren’t aligned to a common baseline. We should never make our audience do more work than necessary to understand a graph!
For example, we use a treemap chart to present new users and view of articles this month.
import squarifyfig = plt.figure(figsize=(10,10))articles = [17, 22, 35, 41, 5, 12, 47]labels = ['User_1:\n 17 articles',          'User_2:\n 22 articles',          'User_3:\n 35 articles',          'User_4:\n 41 articles',          'User_5:\n 5 articles',          'User_6:\n 12 articles',          'User_7:\n 47 articles']color_list = ['#0f7216', '#b2790c', '#ffe9a3',              '#f9d4d4', '#d35158', '#ea3033']plt.rc('font', size=14)        squarify.plot(sizes=articles, label=labels,              color=color_list, alpha=0.7)plt.axis('off')plt.show()
Time-series graphs can be used to visualize trends in counts or numerical values over time. Because date and time information is continuous categorical data (expressed as a range of values), points are plotted along the x-axis and connected by a continuous line.
The goal of time series analysis is to find patterns in the data and use the data for predictions. Time-series graphs can answer questions about our data, such as: How does the trend change over time?
# Time Series Plotplt.figure(figsize=(8,6))ts = pd.Series(np.random.randn(100), index = pd.date_range(                                 '1/1/2020', periods = 100)) # Return the cumulative sum of the elements.ts = ts.cumsum() ts.plot() plt.show()
The code in this note is available on Github.
In this note, we learned how to build data visualization plots using Matplotlib. We can now easily build plots for understanding our data intuitively through visualizations.
Happy studying!
My note just covered all of what I consider to be the basic necessities for Matplotlib. It takes months, sometimes years to master a skill, so, don’t stop learning! If you are eager to learn more about Matplotlib, starting with the great links below.
Customize ticksMatplotlib tutorialMatplotlib galleryMatplotlib user’s guide
Customize ticks
Matplotlib tutorial
Matplotlib gallery
Matplotlib user’s guide