Matplotlib

Also refers to official cheatsheat here

Image Not Showing Possible Reasons
  • The image was uploaded to a note which you don't have access to
  • The note which the image was originally uploaded to has been deleted
Learn More →



Functional OOP
plt.xlabel() ax.set_xlabel()
plt.ylabel() ax.set_ylabel()
plt.xlim() ax.set_xlim()
plt.ylim() ax.set_ylim()
plt.title() ax.set_title()

1. General procedure for plotting

To create a 2D line plot, follow these general steps:

  1. Call the plt.figure() to create a new figure. (optional for %matplotlib inline)
  2. Generate a sequence of
    x
    values usually using linspace().
  3. Generate a sequence of
    y
    values usually by substitute the x values into a function.
  4. Input plt.plot(x, y, [format], **kwargs) where [format] is an (optional) format string, and **kwargs are (optional) keyword arguments specifying the line properties of the plot.
  5. Utilize plt functions to enhance the figure with features such as a title, legend, grid lines, etc.
  6. Input plt.show() to display the resulting figure (this step is optional in a Jupyter notebook).

If your function has a jump (a discontinuity), just place an np.nan at that x-value — Matplotlib will skip it and leave the gap for you.

2. Plots

Creating plots

Figure

Operator Description Documentation
fig = plt.figures() a container that contains all plot elements link

Axes

Operator Description Documentation
fig.add_axes()
a = fig.add_subplot(222)
Initializes subplot
A subplot is an axes on a grid system
row-col-num
link
fig, b = plt.subplots(nrows=3, nclos=2) Adds subplot link
ax = plt.subplots(2, 2) Creates subplot link

Plotting

1D Data

Operator Description Documentation
lines = plt.plot(x,y) Plot data connected by lines link
plt.scatter(x,y) Creates a scatterplot, unconnected data points link
plt.hist(x, y) Plots a histogram link
plt.fill_between(x,y,color='yellow') Fill area under/between plots link

Saving plots

Operator Description Documentation
plt.savefig('pic.png') Saves plot/figure to image link

Customization

Color

Operator Description Documentation
plt.plot(x, y, color='lightblue')
plt.plot(x, y, alpha = 0.4)
colors plot to color blue link
plt.colorbar(mappable, orientation='horizontal') mappable: the Image, Contourset etc to which colorbar applies link

Markers (see examples)

Operator Description Documentation
plt.plot(x, y, marker='*') adds * for every data point link
plt.scatter(x, y, marker='.') adds . for every data point see above

Lines

Operator Description Documentation
plt.plot(x, y, linewidth=2) Sets line width link
plt.plot(x, y, ls='solid') Sets linestyle, ls can be ommitted, see 2 below see above
plt.plot(x, y, ls='--') Sets linestyle, ls can be ommitted, see below see above
plt.plot(x,y,'--', x**2, y**2, '-.') Lines are '' and '_.' see above

Text

Operator Description Documentation
plt.text(1, 1,'Example Text',style='italic') Places text at coordinates 1/1 link
ax.annotate('some annotation', xy=(10, 10)) Annotate the point with coordinatesxy with text s link
plt.title(r'$delta_i=20$', fontsize=10) Mathtext link

Limits, Legends/Labels , Layout

Limits

Operator Description Documentation
plt.xlim(0, 7) Sets x-axis to display 0 - 7 link
plt.ylim(-0.5, 9) Sets y-axis to display -0.5 - 9 link
ax.set(xlim=[0, 7], ylim=[-0.5, 9])
ax.set_xlim(0, 7)
plt.axis('equal') Set the aspect ratio of the plot to 1

Legends/Labels

Operator Description Documentation
plt.title('just a title') Sets title of plot link
plt.xlabel('x-axis') Sets label next to x-axis link
plt.ylabel('y-axis') Sets label next to y-axis link
plt.legend(loc='best') No overlapping plot elements link

Ticks

Operator Description Documentation
plt.xticks(x, labels, rotation='vertical') link

3. Examples

Basics

import matplotlib.pyplot as plt

x = np.linspace(-2,2,200)
plt.plot(x, np.cos(x - 0), color='blue')         # specify color by name
plt.plot(x, np.cos(x - 1), color='g')            # short color code (rgbcmyk)
plt.plot(x, np.cos(x - 2), color='0.75')         # grayscale between 0 and 1
plt.plot(x, np.cos(x - 4), color=(1.0,0.2,0.3)); # RGB tuple, values 0 to 1

Image Not Showing Possible Reasons
  • The image was uploaded to a note which you don't have access to
  • The note which the image was originally uploaded to has been deleted
Learn More →

import matplotlib.pyplot as plt

plt.plot(x, np.sin(x), '-g', label='sin(x)') # solid green line
plt.plot(x, np.cos(x), ':b', label='cos(x)') # dotted blue line

plt.title("A Sin/Cos Curve", fontsize=18)       # we can also specify the font size
plt.xlabel("x", fontsize=14)
plt.ylabel("sin(x)", fontsize=14)
plt.legend(fontsize=12)

plt.axis('equal');

Image Not Showing Possible Reasons
  • The image was uploaded to a note which you don't have access to
  • The note which the image was originally uploaded to has been deleted
Learn More →

import matplotlib.pyplot as plt

plt.plot(x, y, '-vb', markersize=15, linewidth=4, markerfacecolor='orange', markeredgewidth=2)
plt.ylim(-1.2, 1.2);

Image Not Showing Possible Reasons
  • The image was uploaded to a note which you don't have access to
  • The note which the image was originally uploaded to has been deleted
Learn More →

import matplotlib.pyplot as plt

# Plot a normalized (density=True) histogram of the sample `data`
# - 30 equally spaced bins
# - Semi-transparent steel-blue fill (alpha = 0.5)
# - No edges drawn around the bars (edgecolor='none')
plt.hist(data, bins=30, density=True, alpha=0.5,
         color='steelblue', edgecolor='none')
# Create 100 points from -4 to 4 for the x-axis
x = np.linspace(-4, 4, 100)
# Compute the standard normal PDF at each x:
# (1 / sqrt(2π)) * exp(-x² / 2)
y = 1 / (2 * np.pi)**0.5 * np.exp(-x**2 / 2)
# Plot the standard normal curve on top of the histogram
# - Blue line ('b') with slight transparency (alpha = 0.8)
plt.plot(x, y, 'b', alpha=0.8)

Image Not Showing Possible Reasons
  • The image was uploaded to a note which you don't have access to
  • The note which the image was originally uploaded to has been deleted
Learn More →

import matplotlib.pyplot as plt

# Generate 1,000 evenly spaced points over the interval [0, 2π]
x = np.linspace(0, 2 * np.pi, 1000)
# Compute y-values for sine and cosine at each x
y1, y2 = np.sin(x), np.cos(x)
# Boolean mask: True wherever sin(x) is positive
mask = y1 > 0
# Plot sin(x) in red
plt.plot(x, y1, 'r')
# Plot cos(x) in green
plt.plot(x, y2, 'g')
# Shade the region between sin(x) and cos(x)
# (only where sin(x) > 0, thanks to the mask)
plt.fill_between(x, y1, y2, mask, color='red', alpha=0.1)

image

import matplotlib.pyplot as plt

# Create 64 equally spaced angular values in the interval [0, 2π]
t = np.linspace(0, 2*np.pi, 64)
# Radius for each angle: r = sin(t)
r = np.sin(t)
# Plot in polar coordinates
plt.axes(projection='polar')
# For negative r, the point (θ, r) is equivalent to (θ+π, |r|)
# so we shift θ by π wherever r < 0 and take the absolute value of r
plt.plot(t + (r < 0) * np.pi, np.abs(r), '-')
# Set ticks for the polar axis at 0, π/2, π, and 3π/2
plt.xticks([0, np.pi/2, np.pi, 3*np.pi/2],
           ['0', '$\\pi/2$', '$\\pi$', '$3\\pi/2$'])

Subplotting Examples

import matplotlib.pyplot as plt

# Create a Figure (`fig`) with a 2 × 3 grid of Axes objects (`ax`)
fig, ax = plt.subplots(2, 3)
# Adjust the amount of space between rows (hspace) and columns (wspace)
fig.subplots_adjust(hspace=0.4, wspace=0.4)
# Loop over each row index i (0, 1)
for i in range(2):
    # Loop over each column index j (0, 1, 2)
    for j in range(3):
        # Write the coordinates "(i, j)" at the center of the subplot
        #   (0.5, 0.5) are normalized Axes coordinates,
        #   fontsize = 18, and text is horizontally/vertically centered
        ax[i, j].text(0.5, 0.5, str((i, j)),
                      fontsize=18, ha='center', va='center')

Keywords

  • Functional-style Interface (函式風格介面): Also known as the Pyplot interface, this is the simpler way of creating plots in Matplotlib where you directly call plotting functions. It's called "functional-style" because it involves calling functions on the Pyplot module directly and it takes care of creating and managing figures and axes for you.
  • Object-oriented Interface (物件導向介面): This interface is used when you need more control over your figure. Instead of letting Matplotlib handle what the current figure and axes is, you do it yourself. You create Figure and Axes objects and call methods on these objects to manipulate them directly. This makes it easier to create complex layouts and to reuse components.
  • Stateful (具狀態性): Stateful refers to Matplotlib's ability to keep track of the current figure and axes, which are where all plt commands are applied. The interface is stateful because it stores the last created or modified figure and axes as the current one. This is what enables the Functional-style Interface to work.
  • Figure (圖形物件): In Matplotlib, the whole window/page is called the Figure. It's the top-level component that contains all the elements of the plot. A Figure can have several other elements like Axes, Legends, and Titles, among others.
  • Axes (座標區域): These are what you think of as 'a plot'. They are the area in which the data is plotted with functions and can have ticks, labels, etc., associated with it. A figure can contain multiple Axes objects, which can be placed in a grid-like format inside the Figure.
  • Line Plots (折線圖): Line plots are probably one of the most common types of graph. You can use it to visualize the relationship between any two sets of data. For example, you can plot a curve that represents the relationship between temperature (y-axis) and altitude (x-axis).
  • Legends (圖例): Legends help in understanding the plot better. It's an area describing the elements of the graph. In the legend, there are labels along with the represented graphics (lines, points) which are used to depict what they represent in the plot.
  • Format String (格式字串): A format string in Matplotlib is a way to specify colors, markers, and line styles. A format string is a string that contains characters that represent different formatting actions. For example, 'bo-' represents a blue color, circle marker, and solid line style.
  • Scatter Plots (散佈圖): Scatter plots’ primary uses are to observe and show relationships between two numeric variables. The dots in a scatter plot not only report the values of individual data points, but also patterns when the data are taken as a whole.
  • Marker (標記符號): A "marker" in Matplotlib refers to the symbol used in a plot to represent a data point.
  • Colormaps (色彩映射): Colormaps are used to map numerical data to colors in a graph, usually in a gradient-like way. They're used in creating plots like heatmaps or in plots where you'd want to show a gradient of colors. Matplotlib provides a lot of pre-made colormaps for use.
  • Density Plots (密度圖): A density plot is a graphical representation that uses a kernel density estimate to show the probability density function of a random variable. It is a smoothed version of the histogram and improves upon it by dealing with the noise in the data and providing a smooth curve.
  • Ticks: Ticks are the values used to show specific points on the coordinate axis. It 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.
  • Spines (脊線): Spines are lines connecting the axis tick marks and noting the boundaries of the data area. They can be placed at arbitrary positions and until now, were on the border of the axis. In other words, they are the simple lines that denote the boundaries of the plot area – they join the axis tick marks.
  • Subplots (子圖格局): Sometimes we may wish to plot different types of plots (like a density plot, line plot, scatter plot) or multiple instances of the same plot but different data in a single figure. Subplots allow us to do that. They provide an option to plot multiple plots in a single figure.