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:
- Call the
plt.figure()
to create a new figure. (optional for %matplotlib inline
)
- Generate a sequence of values usually using
linspace()
.
- Generate a sequence of values usually by substitute the x values into a function.
- 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.
- Utilize
plt
functions to enhance the figure with features such as a title, legend, grid lines, etc.
- 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
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 →
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 →
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 →
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 →


Subplotting Examples

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.