Show Menu
Cheatography

Matplotlib Cheat Sheet (DRAFT) by

Matplotlib is a library for data visualization in Python

This is a draft cheat sheet. It is a work in progress and is not finished yet.

Line Plots

Line Plots
Line plots are fundam­ental in Matplotlib and are used to visualize data points connected by straight lines. They are partic­ularly useful for displaying trends over time or any ordered data.
Basic Syntax
import matplo­tli­b.p­yplot as plt  
plt.plot(x, y)
plt.show()
Plotting Lines
The plot() function is used to create line plots. Pass arrays of data for the x-axis and y-axis.
Custom­izing Lines
You can customize the appearance of lines using parameters like color, linestyle, and marker.
Multiple Lines
Plot multiple lines on the same plot by calling plot() multiple times before show().
Adding Labels
Always add labels to the axes using xlabel() and ylabel() to provide context to the plotted data.
Example
import matplo­tli­b.p­yplot as plt
Sample data
x = [1, 2, 3, 4, 5] 
y = [2, 4, 6, 8, 10]
Plotting the line
plt.pl­ot(x, y, color=­'blue', 
linestyle='-', marker­='o',
label='Line 1')
Adding labels and title
plt.xl­abe­l('­X-a­xis') 
plt.ylabel('Y-axis')
plt.title('Example Line Plot')
Adding legend
plt.le­gend()
Display plot
plt.show()

Bar Plots

Bar Plots
Bar plots are used to represent catego­rical data with rectan­gular bars. They are commonly used to compare the quantities of different catego­ries. Matplotlib provides a simple way to create bar plots using the bar() function.
Basic Bar Plot:
import matplo­tli­b.p­yplot as plt  
categories = ['A', 'B', 'C', 'D']
values = [25, 30, 35, 40]
plt.bar(categories, values)
plt.xlabel('Categories')
plt.ylabel('Values')
plt.title('Basic Bar Plot')
plt.show()
Custom­izing Bar Plots
You can customize bar plots by changing colors, adding labels, adjusting bar width, and more using various parameters of the bar() function.
Grouped Bar Plots
To compare data across multiple catego­ries, you can create grouped bar plots by plotting multiple sets of bars side by side.
Horizontal Bar Plots
Matplotlib also supports horizontal bar plots using the barh() function. These are useful when you have long category names or want to emphasize certain catego­ries.
Stacked Bar Plots
Stacked bar plots allow you to represent parts of the data as segments of each bar. This is useful for showing the compos­ition of each category.

Handling Missing Data

Check for Missing Data
Before plotting, check your data for any missing values. This can be done using functions like isnull() or isna() from libraries like Pandas or NumPy.
Drop or Impute Missing Values
Depending on your analysis and the nature of missing data, you may choose to either drop the missing values using dropna() or impute them using techniques like mean, median, or interp­ola­tion.
Masking
Matplotlib supports masking, allowing you to ignore specific data points when plotting. You can create a mask array to filter out missing values from your dataset.
Handle Missing Data in Specific Plot Types
Different plot types may have different strategies for handling missing data. For example, in a line plot, you might interp­olate missing values, while in a bar plot, you might choose to leave gaps or replace missing values with zeros.
Commun­icate Missing Data
Make sure your plots commun­icate clearly when data is missing. You can use annota­tions or legends to indicate where data has been removed or imputed.

Pie Charts

Pie Charts
Pie charts are circular statis­tical graphics that are divided into slices to illustrate numerical propor­tions. Each slice represents a propor­tionate part of the whole data set.
Usage
Ideal for displaying the relative sizes of various categories within a dataset.
Best suited for repres­enting data with fewer categories (around 6 or fewer) to maintain clarity.
Creating a Pie Chart
import matplo­tli­b.p­yplot as plt  
labels = ['Category 1', 'Category 2', 'Category 3']
sizes = [30, 40, 30]
# Propor­tions of each category
plt.pie(sizes, labels­=la­bels, autopc­t='­%1.1­f%%')
plt.axis('equal')
# Equal aspect ratio ensures that pie is drawn as a circle.
plt.show()
Custom­ization
Colors: You can specify custom colors for each slice.
Exploding Slices: Emphasize a particular slice by pulling it out of the pie.
Labels: Adjust label font size, color, and position.
Shadow: Add a shadow effect for better visual appeal.
Legend: Include a legend to clarify the meaning of each slice.
Example
# Custom­izing a Pie Chart 
colors = ['gold', 'yellowgreen',
'light­coral']
explode = (0, 0.1, 0)
# Explode the 2nd slice (Category 2)
plt.pie(sizes, explod­e=e­xplode,
labels=labels, colors­=co­lors,
autopct='%1.1f%%', shadow­=True)
plt.axis('equal')
plt.show()
Consid­era­tions
Avoid using pie charts for datasets with many catego­ries, as slices become small and difficult to interpret.
Ensure that the propor­tions of the data are clear and easy to unders­tand.
Double­-check labels and legend to avoid confusion.

Custom­izing Plots

Custom­izing Plots
You can customize the color, linestyle, and marker style of lines and markers using parameters like color, linestyle, and marker.
Line and Marker Properties
Adjust the width of lines with the linewidth parameter and the size of markers with marker­size.
Axes Limits
Set the limits of the x and y axes using xlim and ylim to focus on specific regions of your data.
Axis Labels and Titles
Add descri­ptive labels to the x and y axes using xlabel and ylabel, and give your plot a title with title.
Grids
Display grid lines on your plot using grid.
Legends
Add a legend to your plot to label different elements using legend.
Ticks
Customize the appearance and positi­oning of ticks on the axes using functions like xticks and yticks.
Text Annota­tions
Annotate specific points on your plot with text using text or annotate.
Figure Size
Adjust the size of your figure using the figsize parameter when creating a figure.
Background Color
Change the background color of your plot using set_fa­cec­olor.

Introd­uction to Matplotlib

Matplotlib is a powerful Python library widely used for creating static, intera­ctive, and public­ati­on-­quality visual­iza­tions. It provides a flexible and compre­hensive set of plotting tools for generating a wide range of plots, from simple line charts to complex 3D plots.
Key Features:
Simple Interface: Matplotlib offers a straig­htf­orward interface for creating plots with just a few lines of code.
Flexib­ility: Users have fine-g­rained control over the appearance and layout of their plots, allowing for custom­ization according to specific needs.
Wide Range of Plot Types: Matplotlib supports various plot types, including line plots, scatter plots, bar plots, histog­rams, pie charts, and more.
Integr­ation with NumPy: Matplotlib seamlessly integrates with NumPy, making it easy to visualize data stored in NumPy arrays.
Public­ati­on-­Quality Output: Matplotlib produces high-q­uality, public­ati­on-­ready plots suitable for both digital and print media.
Extens­ibi­lity: Users can extend Matplo­tlib's functi­onality through its object­-or­iented interface, enabling the creation of custom plot types and enhanc­ements.
import matplo­tli­b.p­yplot as plt  
# Sample data
x = [1, 2, 3, 4, 5]
y = [2, 4, 6, 8, 10]
# Create a line plot
plt.plot(x, y)
plt.xlabel('X-axis label')
plt.ylabel('Y-axis label')
plt.title('Simple Line Plot')
plt.show()

Annota­tions and Text

Adding Text
plt.te­xt(x, y, 'Your Text Here', fontsi­ze=12, color=­'blue')
Annota­tions
plt.an­not­ate­('I­mpo­rtant Point', 
xy=(x, y), xytext­=(x­_text, y_text),
arrowprops=dict(facecolor='black',
arrowstyle='->'), fontsi­ze=10)
Text Properties
Matplotlib allows you to customize text properties such as font size, color, and style. Use keyword arguments like fontsize, color, fontwe­ight, etc., to modify text appear­ance.
Latex Support
plt.te­xt(x, y, 
r'$\alpha > \beta$', fontsi­ze=12)
Multiline Text
plt.te­xt(x, y, 'Line 1\nLine 2', 
fontsize=12)
Rotation
plt.te­xt(x, y, 'Rotated Text', 
fontsize=12, rotati­on=45)

Advanced Plotting Techniques

Multiple Axes and Figures
Use plt.su­bpl­ots() to create multiple plots in a single figure. Control layout with plt.su­bplot() or plt.Gr­idS­pec().
Custom­izing Line Styles
Change line styles with linestyle parameter (e.g., '-', '--', '-.', ':'). Adjust line width using linewidth.
Color Mapping and Colormaps
Utilize colormaps for visual­izing data with color gradients. Apply colormaps using the cmap parameter in functions like plt.sc­atter() or plt.im­show().
Error Bars and Confidence Intervals
Represent uncert­ainties in data with error bars. Add error bars using plt.er­ror­bar() or ax.err­orb­ar().
Layering Plots
Overlay plots to visualize multiple datasets in one figure. Use plt.plot() or ax.plot() multiple times with different data.
Plotting with Logari­thmic Scale
Use logari­thmic scales for axes with plt.xs­cale() and plt.ys­cale(). Helpful for visual­izing data that spans several orders of magnitude.
Polar Plots
Create polar plots with plt.su­bplot() and projec­tio­n='­polar'. Useful for visual­izing cyclic data, such as compass directions or periodic phenomena.
3D Plotting
Visualize 3D data with mpl_to­olk­its.mp­lot3d. Create 3D scatter plots, surface plots, and more.
Animations
Animate plots using FuncAn­ima­tion. Ideal for displaying dynamic data or simula­tions.
Stream­plots
Visualize vector fields with stream­lines using plt.st­rea­mpl­ot(). Useful for displaying fluid flow or electr­oma­gnetic fields.

Intera­ctive Plotting

Zooming and Panning
Users can zoom in on specific regions of the plot to examine details more closely or pan across the plot to explore different sections.
Data Selection
Intera­ctive plots allow users to select and highlight specific data points or regions of interest within the plot.
Intera­ctive Widgets
Matplotlib provides widgets such as sliders, buttons, and text input boxes that enable users to dynami­cally adjust plot parame­ters, such as plot range, line styles, or data filters.
Dynamic Updates
Plots can update dynami­cally in response to user intera­ctions or changes in the underlying data, providing real-time feedback and visual­iza­tion.
Custom Intera­ctivity
Users can define custom intera­ctive behavior using Matplo­tlib's event handling system, allowing for complex intera­ctions tailored to specific use cases.
 

Adding Labels and Titles

Adding Axis Labels
plt.xl­abe­l("X­-axis Label") 
plt.ylabel("Y-axis Label")
Adding Titles
plt.ti­tle­("Plot Title")
Custom­izing Labels and Titles
plt.xl­abe­l("X­-axis Label", 
fontsize=12, fontwe­igh­t='­bold',
color='blue')
plt.title("Plot Title",
fontsize=14, fontwe­igh­t='­bold',
color='green')
Mathem­atical Expres­sions in Labels
plt.xl­abe­l(r­"­$\a­lph­a$") 
plt.title(r"$\beta$")

3D Plotting

To create a 3D plot in Matplo­tlib, you typically start by importing the necessary modules:
import matplo­tli­b.p­yplot as plt 
from mpl_to­olk­its.mp­lot3d import Axes3D
Then, you can create a 3D axes object using plt.fi­gure() and passing the projec­tio­n='3d' argument:
fig = plt.fi­gure() 
ax = fig.ad­d_s­ubp­lot­(111,
projection='3d')
Once you have your 3D axes object, you can plot various types of 3D data using methods such as plot(), scatter(), bar3d(), etc. For example, to create a simple 3D scatter plot:
ax.sca­tte­r(x­_data, y_data, z_data)
You can also customize the appearance of your 3D plot by setting properties such as labels, titles, axis limits, colors, and more:
ax.set­_xl­abel('X Label') 
ax.set_ylabel('Y Label')
ax.set_zlabel('Z Label')
ax.set_title('3D Scatter Plot')
# Set axis limits
ax.set_xlim(x_min, x_max)
ax.set_ylim(y_min, y_max)
ax.set_zlim(z_min, z_max)
# Customize colors
ax.scatter(x_data, y_data,
z_data, c=colo­r_data,
cmap='viridis')

Plotting Images

Example
import matplo­tli­b.p­yplot as plt 
import numpy as np
Create a random image
image_data = np.random.random((
100, 100))
Plot the image
plt.im­sho­w(i­mag­e_data, cmap='­gray') 
plt.axis('off')
# Turn off axis
plt.show()

Working with Different Plot Styles

Default Style
Matplo­tlib's default style is functional and simple. Suitable for most basic plots without any specific styling requir­ements.
FiveTh­irt­yEight Style
Mimics the style used by the FiveTh­irt­yEight website. Bold colors and thicker lines for emphasis.
ggplot Style
Emulates the style of plots generated by the ggplot library in R. Clean and modern appearance with gray backgr­ounds.
Seaborn Style
Similar to the default Seaborn plotting style. Features muted colors and grid backgr­ounds.
Dark Background Styles
Various styles with dark backgr­ounds, suitable for presen­tations or dashbo­ards. Examples include 'dark_­bac­kgr­ound' and 'Solar­ize­_Li­ght2'.
XKCD Style
Creates plots with a hand-d­rawn, cartoonish appear­ance. Adds a playful touch to visual­iza­tions.
Example
import matplo­tli­b.p­yplot as plt  
plt.style.use('ggplot')

Saving Plots

Using savefig() Function
import matplo­tli­b.p­yplot as plt  
# Plotting code here
plt.savefig('plot.png')
# Save the plot as 'plot.png'
Custom­izing Output
plt.sa­vef­ig(­'pl­ot.p­ng', dpi=300, 
bbox_inches='tight',
transparent=True)
Supported Formats
plt.sa­vef­ig(­'pl­ot.p­df')  
# Save as PDF
plt.savefig('plot.svg')
# Save as SVG
Intera­ctive Saving
plt.sa­vef­ig(­'pl­ot.p­ng', 
bbox_inches='tight',
pad_inches=0)

Legends

For example:
import matplo­tli­b.p­yplot as plt
Plotting data
plt.pl­ot(x1, y1, label=­'Line 1') 
plt.plot(x2, y2, label=­'Line 2')
Adding legend
plt.le­gend() 
plt.show()
You can customize the appearance of the legend by specifying its location, adjusting the font size, changing the background color, and more.
plt.le­gen­d(l­oc=­'upper right', 
fontsize='large', shadow­=True,
facecolor='lightgray')

Subplots

Subplots
Subplots allow you to display multiple plots within the same figure. This is useful for comparing different datasets or visual­izing related inform­ation.
Creating Subplots
import matplo­tli­b.p­yplot as plt  
# Create a figure with 2 rows and 2 columns of subplots
fig, axs = plt.su­bpl­ots(2, 2)
Accessing Subplot Axes
ax1 = axs[0, 0]  
# Top-left subplot
ax2 = axs[0, 1]
# Top-right subplot
ax3 = axs[1, 0]
# Bottom­-left subplot
ax4 = axs[1, 1]
# Bottom­-right subplot
Plotting on Subplots
ax1.pl­ot(x1, y1) 
ax2.scatter(x2, y2)
ax3.bar(x3, y3)
ax4.hist(data)
Custom­izing Subplots
ax1.se­t_t­itl­e('Plot 1') 
ax2.set_xlabel('X Label')
ax3.set_ylabel('Y Label')
Adjusting Layout
plt.su­bpl­ots­_ad­jus­t(h­spa­ce=0.5, wspace­=0.5)  
# Adjust horizontal and vertical spacing
Conclusion
Subplots are a powerful feature in Matplotlib for creating multi-­panel figures, allowing you to effici­ently visualize and compare multiple datasets within the same plot.

Histograms

Histograms
Histograms are graphical repres­ent­ations of the distri­bution of data. They display the frequency or probab­ility of occurrence of different values in a dataset, typically depicted as bars. Histograms are commonly used to visualize the distri­bution of continuous data.
Creating a Histogram
import matplo­tli­b.p­yplot as plt  
data = [1, 2, 3, 3, 4, 4, 4, 5, 5, 6, 7, 7,
8, 8, 8]
plt.hist(data, bins=5, color=­'sk­yblue',
edgecolor='black')
plt.xlabel('Values')
plt.ylabel('Frequency')
plt.title('Histogram of Data')
plt.show()
Parameters
data: The input data to be plotted.
bins: Number of bins or intervals for the histogram.
color: Color of the bars.
edgecolor: Color of the edges of the bars.
Custom­iza­tions
Adjust the number of bins to control the granul­arity of the histogram.
Change colors, edge colors, and bar width for aesthetic appeal.
Add labels and titles for clarity.
Interp­ret­ation
Histograms help in unders­tanding the distri­bution of data, including its central tendency, spread, and shape.
They are useful for identi­fying patterns, outliers, and data skewness.
Histograms are often used in explor­atory data analysis and statis­tical analysis.

Scatter Plots

Scatter Plot
A Scatter Plot is a type of plot that displays values for two variables as points on a Cartesian plane. Each point represents an observ­ation in the dataset, with the x-coor­dinate corres­ponding to one variable and the y-coor­dinate corres­ponding to the other variable.
Visual­izing Relati­onships
Scatter plots are partic­ularly useful for visual­izing relati­onships or patterns between two variables. They can reveal trends, clusters, correl­ations, or outliers in the data.
Marker Style and Color
Points in a scatter plot can be customized with different marker styles, sizes, and colors to enhance visual­ization and highlight specific data points or groups.
Adding Third Dimension
Sometimes, scatter plots can incorp­orate additional dimensions by mapping variables to marker size, color intensity, or shape.
Regression Lines
In some cases, regression lines or curves can be added to scatter plots to indicate the overall trend or relati­onship between the variables.
Example
import matplo­tli­b.p­yplot as plt
Sample data
x = [1, 2, 3, 4, 5] 
y = [2, 3, 5, 7, 11]
Create a scatter plot
plt.sc­att­er(x, y, color=­'blue', 
marker='o', s=100)
Adding labels and title
plt.xl­abe­l('­X-axis Label') 
plt.ylabel('Y-axis Label')
plt.title('Scatter Plot Example')
Show plot
plt.show()
Data Scaling
Ensure that both variables are on a similar scale to avoid distortion in the visual­iza­tion.
Data Explor­ation
Use scatter plots as an initial step in data explor­ation to identify potential patterns or relati­onships before further analysis.
Interp­ret­ation
Interp­ret­ation of scatter plots should consider the overall distri­bution of points, any evident trends or clusters, and the context of the data.

Basic Plotting

Importing Matplotlib
import matplo­tli­b.p­yplot as plt
Creating a Plot
plt.pl­ot(­x_v­alues, y_values)
Displaying the Plot
plt.show()
Adding Labels and Title
plt.xl­abe­l('­X-axis Label') 
plt.ylabel('Y-axis Label')
plt.title('Plot Title')
Custom­izing Plot Appearance
plt.pl­ot(­x_v­alues, y_values, 
color='red', linest­yle­='--',
marker='o')
Adding Gridlines
plt.gr­id(­True)
Saving the Plot
plt.sa­vef­ig(­'pl­ot.p­ng')

Plotting with Dates

Datetime Objects
Matplotlib accepts datetime objects for plotting dates. You can create datetime objects using Python's datetime module.
Date Formatting
You can customize the appearance of dates on the plot using formatting strings. Matplo­tlib's DateFo­rmatter class enables you to specify the format of date labels.
Plotting Time Series
Matplotlib provides various plotting functions like plot(), scatter(), and bar() that accept datetime objects as input for the x-axis.
Custom­izing Date Axes
You can customize the appearance of the date axis, including the range, tick frequency, and format­ting. Matplo­tlib's DateLo­cator class helps in config­uring date ticks on the axis.
Handling Time Zones
Matplotlib supports handling time zones in date plotting. You can convert datetime objects to different time zones using Python libraries like pytz and then plot them accord­ingly.
Plotting Date Ranges
Matplotlib allows you to plot specific date ranges by filtering your dataset based on date values before passing them to the plotting functions.