To plot a single plot, and to plot multiple subplots with different styles, this article is enough
Matplotlib. pyplot is a collection of functions that make Matplotlib work like MATLAB. This blog will introduce
- Single figure single
- Single drawing with different lines (red circle, blue solid line, green triangle, etc.)
- Draw with keyword strings (data can be specified as numpy. Recarray or pandas.DataFrame)
- Drawing with classification variables (bar, scatter, line)
- Multi-sub-table multi-axis and shared axis
- Multiple subtables (horizontal stacked, vertical stacked, horizontal vertical stacked, horizontal vertical stacked shared axis, horizontal vertical stacked remove redundant XY labels and gaps in the middle of the subgraph, polar coordinate style axis example);
-
The plt.set_title(‘ simple plot ‘, loc = ‘left’) setting represents the title, which defaults to the middle and can also be left and right
-
T = plt.xlabel(‘Smarts’, fontsize=14, color=’red’) sets the text, fontsize, and color of the xlabel
-
Plt.plot ([1, 2, 3, 4]) If a single list or array is supplied, matplot assumes the value of y is supplied; X is the same as y by default, but starts from 0, indicating x:[0,1,2,3]
-
PLT. The plot ([1, 2, 3, 4], [1, 4, 9, 16]) x said: [1, 2, 3, 4], y:,4,9,16 [1]
-
PLT. The plot ([1, 2, 3, 4], [1, 4, 9, 16], ‘ro’) x said: [1, 2, 3, 4], y:,4,9,16 [1], and then specify the line color, and style (ro: red circle, b – : blue lines, etc.)
-
Plt. axis([0, 6, 0,20]) plt.axix[xmin, xmax, ymin, ymax] represents the scale range of x axis [0,6] and y axis [0,20].
-
Plt. bar(names, values) # bar graph
-
Plt. scatter(names, values) # Scatter
-
Plt.plot (names, values) # Line chart
-
The plots of ax = PLT. Subplots (2, sharex=True, sharey=True) will be used to plot the plots. The plots of ax[0] and AX [1] will be used to plot the plots
-
(ax1, ax2) = PLT. Subplots (2, sharex=True, sharey=True)
-
(ax1, ax2) = PLT. Subplots (2, sharex=True, sharey=True)
-
(ax1, ax2) = PLT. Subplots (1, 2, sharex=True, sharey=True)
-
Ax1, ax2 = PLT. Subplots (2, 2, sharex=True, sharey=True, hspace=0, wspace=0), ax1, ax2 = PLT. And remove the gap between the width and height of the subgraph
Shared x and y axes represent the scale and range of shared X and y axes;
- PLT. Text (60, 025, r ’15 \ mu mu = 100, sigma = = 100, \ \ sigma = 15 mu = 100, sigma = 15′) said in the 60 s, Note the text (μ=100, σ=15\mu=100,\ \sigma=15μ=100, σ=15) at 0.025
1. Single picture and single line
# Single graph single line
import matplotlib.pyplot as plt
# If you provide a single list or array, Matplotlib assumes it is a sequence of Y values and automatically generates x values for you.
Since python ranges start at 0, the default x vector has the same length as y, but starts at 0. So x data is [0, 1, 2, 3]
plt.plot([1.2.3.4])
plt.ylabel('some numbers')
plt.show()
plt.plot([1.2.3.4], [1.4.9.16])
plt.show()
# For each pair of x, y arguments, there is an optional third argument, which is a format string indicating the color and line of the drawing.
# Format string letters and symbols from MATLAB, connect color string with linear string. The default format string is "B -", which is a solid blue line. 'ro' red circle
plt.plot([1.2.3.4], [1.4.9.16].'ro')
plt.axis([0.6.0.20]) # Scale axis range, x: 0~6, y: 0~20
plt.show()
Copy the code
2. Different styles of single picture and multiple lines (red circle, blue solid line, green triangle, etc.)
- ‘B -‘ : solid blue line
- ‘ro’ : red circle
- ‘r–‘ : red dash
- ‘BS’ : blue square
- ‘G ^’ : Green triangle
Please refer to the color and style of the line
Mark sign:
‘.’ point marker
‘,’ pixel marker ‘o’ circle marker ‘v’ triangle_down marker ‘^’ triangle_up marker ‘<‘ triangle_left marker ‘>’ triangle_right marker ‘1’ tri_down marker ‘2’ tri_up marker ‘3’ tri_left marker ‘4’ tri_right marker ‘8’ octagon marker ‘s’ square marker ‘p’ pentagon marker ‘P’ plus (filled) marker ‘*’ star marker ‘h’ hexagon1 marker ‘H’ hexagon2 marker ‘+’ plus marker ‘x’ x marker ‘X’ x (filled) marker ‘D’ diamond marker ‘d’ thin_diamond marker ‘|’ vline marker ‘_’ hline marker
- Supported colors:
‘b’ blue blue
‘g’ green ‘R’ red ‘c’ cyan ‘M’ magenta purple ‘y’ yellow yellow ‘k’ black black ‘W’ white White
- Supported point styles:
‘-‘ solid line style
‘–‘ dashed line style ‘-.’ Dash -dot line style ‘:’ dotted line style
import matplotlib.pyplot as plt
import numpy as np
Sample time evenly at 200 ms intervals
t = np.arange(0..5..0.2)
# 'r--': red dash, 'BS ': blue square, 'g^' : green triangle
plt.plot(t, t, 'r--', t, t ** 2.'bs', t, t ** 3.'g^')
plt.show()
Copy the code
3. Draw data with the keyword string (numpy. Recarray or pandas.DataFrame)
import matplotlib.pyplot as plt
import numpy as np
# use the keyword string to draw (data can be specified as: numpy. Recarray or pandas.DataFrame)
data = {'a': np.arange(50), # 1 parameter representing [0,1,2... 50]
'c': np.random.randint(0.50.50), Generate 50 random numbers [0,50]
'd': np.random.randn(50)} # return values with standard normal distribution (either positive or negative)
data['b'] = data['a'] + 10 * np.random.randn(50)
data['d'] = np.abs(data['d']) * 100
print(np.arange(50))
print(np.random.randint(0.50.50))
print(np.random.randn(50))
print(data['b'])
print(data['d'])
plt.scatter('a'.'b', c='c', s='d', data=data)
plt.xlabel('entry a')
plt.ylabel('entry b')
plt.show()
Copy the code
4. Drawing with classification variables (bar chart, scatter chart, broken line chart)
- Plt. bar(names, values) # bar graph
- Plt. scatter(names, values) # Scatter
- Plt.plot (names, values) # Line chart
import matplotlib.pyplot as plt
import numpy as np
# Draw with classification variables
names = ['group_a'.'group_b'.'group_c']
values = [1.10.100]
plt.figure(figsize=(9.3))
plt.subplot(131)
plt.bar(names, values) # bar graph
plt.subplot(132)
plt.scatter(names, values) # a scatter diagram
plt.subplot(133)
plt.plot(names, values) # line chart
plt.suptitle('Categorical Plotting')
plt.show()
Lines have a number of properties that can be set: line width, dashed line style, anti-aliasing, etc.
lines = plt.plot(10.20.30.100)
# use keyword args
plt.setp(lines, color='r', linewidth=2.0)
# or MATLAB style string value pairs
plt.setp(lines, 'color'.'r'.'linewidth'.2.0)
line, = plt.plot(np.arange(50), np.arange(50) + 10.The '-')
plt.show()
Copy the code
5. Multiple sub-tables with multiple axes and shared axes
Multi-sub-table multi-axis, first with point and then with line connection, the effect picture is as follows: Multi-sub-table multi-axis, drawing point renderings as follows:
import matplotlib.pyplot as plt
import numpy as np
# Multitable and multiaxis
def f(t) :
return np.exp(-t) * np.cos(2 * np.pi * t)
t1 = np.arange(0.0.5.0.0.1)
t2 = np.arange(0.0.5.0.0.02)
plt.figure()
plt.subplot(211) 2,1,1 = 211
plt.plot(t1, f(t1), 'bo', t2, f(t2), 'k') Draw the blue circle (T1, f(t1)) and then connect the values with a black line
plt.subplot(212)
plt.plot(t2, np.cos(2 * np.pi * t2), 'r--')
plt.show()
# Remove T2 from FIG. 1, and f(T2) does not connect the results
plt.figure()
plt.subplot(211) 2,1,1 = 211
plt.plot(t1, f(t1), 'bo')
plt.subplot(212)
plt.plot(t2, np.cos(2 * np.pi * t2), 'r--')
plt.show()
Copy the code
Multiple sub-tables share Y-axis, and the effect picture is as follows:
(ax1, ax2) = PLT. Subplots (2, sharey=True)
Multiple subtables share axes
import numpy as np
import matplotlib.pyplot as plt
# Build drawing data
x1 = np.linspace(0.0.5.0)
x2 = np.linspace(0.0.2.0)
y1 = np.cos(2 * np.pi * x1) * np.exp(-x1)
y2 = np.cos(2 * np.pi * x2)
Draw two subgraphs sharing the Y-axis
fig, (ax1, ax2) = plt.subplots(2, sharey=True)
ax1.plot(x1, y1, 'ko-')
ax1.set(title='A tale of 2 subplots', ylabel='Damped oscillation')
ax2.plot(x2, y2, 'r.-')
ax2.set(xlabel='time (s)', ylabel='Undamped')
plt.show()
Copy the code
6. Many children table
6.1 Multiple Subtables Are Stacked Vertically
6.2 Multiple Sub-tables Are Stacked Horizontally
6.3 Multiple Subtables Are Stacked Vertically and horizontally
Hide the X label of the top 2 subgraphs and the Y label of the right 2 subgraphs. The effect picture is as follows: Same as above, share x column, y row coordinate axis ~
6.4 Sharing axis of multiple subtables (remove gaps between width and height between vertical and horizontal stacked subtables)
Share the X-axis and align it as follows: The effect of sharing x and y axes is shown below:
Share x, y axis represents share its range and scale;
For a shared axis subgraph, a set of scale labels is sufficient. The scale labels for the internal axes are automatically removed by Sharex and Sharey. There is still an unused empty space between the subgraphs;
To precisely control the positioning of the subgraphs, use FIG. Add_gridspec (hspace=0) to reduce the height between the vertical subgraphs. FIG. Add_gridspec (wspace=0) reduces the height between horizontal subgraphs.
Share x and y axes and delete height gaps between multiple subtables, resulting in the following image: Share x and Y axes and delete redundant XY labels of multiple subtables, as well as gaps of width and height between subgraphs. The effect is shown as follows:
6.5 Multi-subtable Polar Coordinate Style axis
6.6 Multiple subtables source code
Remove the redundant XY labels and gaps in the middle of the subgraph;
import matplotlib.pyplot as plt
import numpy as np
# Sample data
x = np.linspace(0.2 * np.pi, 400)
y = np.sin(x ** 2)
def single_plot() :
fig, ax = plt.subplots()
ax.plot(x, y)
ax.set_title('A single plot')
plt.show()
def stacking_plots_one_direction() :
The first two optional parameters of the subplot define the number of rows and columns in the subplot grid.
# When stacked in only one direction, the axis returned is a one-dimensional NUMPY array containing the list of axes created.
fig, axs = plt.subplots(2)
fig.suptitle('Vertically stacked subplots')
axs[0].plot(x, y)
axs[1].plot(x, -y)
plt.show()
# When only a few Axes are created, it would be convenient to immediately unzip them into the special variables for each Axes
fig, (ax1, ax2) = plt.subplots(2)
fig.suptitle('Vertically stacked subplots')
ax1.plot(x, y)
ax2.plot(x, -y)
plt.show()
# Stack subgraphs horizontally
fig, (ax1, ax2) = plt.subplots(1.2)
fig.suptitle('Horizontally stacked subplots')
ax1.plot(x, y)
ax2.plot(x, -y)
plt.show()
def stacking_plots_two_directions() :
# When stacking subgraphs in both directions, the axs returned is a 2D NumPy array. A table representing two rows and two columns
fig, axs = plt.subplots(2.2)
axs[0.0].plot(x, y)
axs[0.0].set_title('Axis [0, 0]')
axs[0.1].plot(x, y, 'tab:orange')
axs[0.1].set_title('Axis [0, 1]')
axs[1.0].plot(x, -y, 'tab:green')
axs[1.0].set_title('Axis [1, 0]')
axs[1.1].plot(x, -y, 'tab:red')
axs[1.1].set_title('Axis [1, 1]')
for ax in axs.flat:
ax.set(xlabel='x-label', ylabel='y-label')
# Hide the X tag of the top 2 subgraphs, and the Y tag of the right 2 subgraphs
for ax in axs.flat:
ax.label_outer()
plt.show()
It is also possible to use tuple unpacking in 2D to assign all subgraphs to special variables
fig, ((ax1, ax2), (ax3, ax4)) = plt.subplots(2.2)
fig.suptitle('Sharing x per column, y per row')
ax1.plot(x, y)
ax2.plot(x, y ** 2.'tab:orange')
ax3.plot(x, -y, 'tab:green')
ax4.plot(x, -y ** 2.'tab:red')
for ax in fig.get_axes():
ax.label_outer()
plt.show()
def sharing_axs() :
fig, (ax1, ax2) = plt.subplots(2)
fig.suptitle('Axes values are scaled individually by default')
ax1.plot(x, y)
ax2.plot(x + 1, -y)
plt.show()
# Share X-axis, align X-axis
fig, (ax1, ax2) = plt.subplots(2, sharex=True)
fig.suptitle('Aligning x-axis using sharex')
ax1.plot(x, y)
ax2.plot(x + 1, -y)
plt.show()
# Share the x and y axes
fig, axs = plt.subplots(3, sharex=True, sharey=True)
fig.suptitle('Sharing both axes')
axs[0].plot(x, y ** 2)
axs[1].plot(x, 0.3 * y, 'o')
axs[2].plot(x, y, '+')
plt.show()
# For a shared axis subgraph, a set of graduated labels is sufficient. The scale labels for the internal axes are automatically removed by Sharex and Sharey. There is still an unused empty space between the subgraphs;
To precisely control the positioning of the subgraph, you can explicitly create a GridSpec with figure.add_gridSpec and then call the subgraph method. For example, you can use add_gridspec(hspace=0) to reduce the height between vertical subgraphs.
fig = plt.figure()
gs = fig.add_gridspec(3, hspace=0)
axs = gs.subplots(sharex=True, sharey=True)
fig.suptitle('Sharing both axes')
axs[0].plot(x, y ** 2)
axs[1].plot(x, 0.3 * y, 'o')
axs[2].plot(x, y, '+')
Hide the x label and scale of all subgraphs except the bottom X label and scale
# label_outer is a convenient way to remove labels and scales from subgraphs of grid edges.
for ax in axs:
ax.label_outer()
plt.show()
# 2*2 multiple graphs are stacked, sharing x and y axes and removing gaps between the width and height of the subgraphs
fig = plt.figure()
gs = fig.add_gridspec(2.2, hspace=0, wspace=0)
(ax1, ax2), (ax3, ax4) = gs.subplots(sharex='col', sharey='row')
fig.suptitle('Sharing x per column, y per row')
ax1.plot(x, y)
ax2.plot(x, y ** 2.'tab:orange')
ax3.plot(x + 1, -y, 'tab:green')
ax4.plot(x + 2, -y ** 2.'tab:red')
for ax in axs.flat:
ax.label_outer()
plt.show()
# Shared axis code for complex structures
fig, axs = plt.subplots(2.2)
axs[0.0].plot(x, y)
axs[0.0].set_title("main")
axs[1.0].plot(x, y ** 2)
axs[1.0].set_title("shares x with main")
axs[1.0].sharex(axs[0.0])
axs[0.1].plot(x + 1, y + 1)
axs[0.1].set_title("unrelated")
axs[1.1].plot(x + 2, y + 2)
axs[1.1].set_title("also unrelated")
fig.tight_layout()
plt.show()
def polar_axs() :
fig, (ax1, ax2) = plt.subplots(1.2, subplot_kw=dict(projection='polar'))
ax1.plot(x, y)
ax2.plot(x, y ** 2)
plt.title('polar axs')
plt.show()
# only single table
single_plot()
Only one way to stack subtables (vertical, horizontal)
stacking_plots_one_direction()
# Horizontal and vertical stack subgraph
stacking_plots_two_directions()
# share shaft
sharing_axs()
# Polar coordinate style axis
polar_axs()
Copy the code
7. Annotation of Chinese text of chart (arrow annotation)
Simple text annotation (only set the text content to be marked and the starting position), the effect picture is as follows:
$\mu=100,\ \sigma=15$');
The r before the # string is important -- it indicates that the string is a raw string, rather than treating the backslash as a Python escape
plt.text(60.025..r'$\mu=100,\ \sigma=15$')
Copy the code
The effect picture of the text annotation arrow is as follows :(you need to set the starting position of the arrow, the starting position of the text and the text value)
A common use of text is to annotate certain features of a drawing, and the Annotate method provides helper functions to simplify annotation.
In comments, there are two things to consider: the position of the comment, represented by the argument xy, and the position of the text xytext. Both of these arguments are (x, y) tuples.
plt.annotate('local max', xy=(2.1), xytext=(3.1.5),
arrowprops=dict(facecolor='yellow', shrink=0.05),Copy the code
# Text tagging
import matplotlib.pyplot as plt
import numpy as np
Simple text comments
def simplt_text() :
mu, sigma = 100.15
x = mu + sigma * np.random.randn(10000)
# Histogram data
n, bins, patches = plt.hist(x, 50, density=1, facecolor='g', alpha=0.75)
# Set the text, font size, and color of the X tag
t = plt.xlabel('Smarts', fontsize=14, color='red')
plt.ylabel('Probability')
plt.title('Histogram of IQ', loc='left')
# indicates that text ('$\mu=100,\ \sigma=15$') is annotated at 60,0.025. The r before the string is important -- it indicates that the string is a raw string, rather than treating the backslash as a python escape
plt.text(60.025..r'$\mu=100,\ \sigma=15$')
plt.axis([40.160.0.0.03])
plt.grid(True)
plt.show()
# Arrow text annotation
def annotation_text() :
ax = plt.subplot()
t = np.arange(0.0.5.0.0.01)
s = np.cos(2 * np.pi * t)
line, = plt.plot(t, s, lw=2)
A common use of text is to annotate certain features of a drawing, and the Annotate method provides helper functions to simplify annotation.
# In comments, there are two points to consider: xy: arrow position, xytext: text position. Both of these arguments are (x, y) tuples.
plt.annotate('local max', xy=(2.1), xytext=(3.1.5),
arrowprops=dict(facecolor='yellow', shrink=0.05),
)
plt.ylim(-2.2)
plt.show()
Simple text comments
simplt_text()
# Arrow text annotation
annotation_text()
Copy the code
8. Logarithmic axis and other nonlinear axes
Linear axis VS logarithmic axis VS linear symmetry axis VS Logit axis:
# matplotlib.pyplot supports not only linear axis scaling, but also logarithmic and logit scaling
import matplotlib.pyplot as plt
import numpy as np
# Linear log axis symmetric log axis logit axis
def logit_plot() :
# Set seeds to ensure random repeatability
np.random.seed(19680801)
# add some data to the open interval (0,1)
Extract random samples from a normal (Gaussian) distribution
y = np.random.normal(loc=0.5, scale=0.4, size=1000)
y = y[(y > 0) & (y < 1)]
y.sort()
x = np.arange(len(y))
Draw data for different axis dimensions
plt.figure()
# linear
plt.subplot(221)
plt.plot(x, y)
plt.yscale('linear')
plt.title('linear')
plt.grid(True)
# logarithmic
plt.subplot(222)
plt.plot(x, y)
plt.yscale('log')
plt.title('log')
plt.grid(True)
# Symmetric log Indicates the axis of symmetric objects
plt.subplot(223)
plt.plot(x, y - y.mean())
plt.yscale('symlog', linthresh=0.01)
plt.title('symlog')
plt.grid(True)
# logit
plt.subplot(224)
plt.plot(x, y)
plt.yscale('logit')
plt.title('logit')
plt.grid(True)
# adjust the layout of the subgraph, because logit takes up more space than the others, y in "1-10 ^{-3}"
plt.subplots_adjust(top=0.92, bottom=0.08, left=0.10, right=0.95, hspace=0.25,
wspace=0.35)
plt.show()
# matplotlib.pyplot supports not only linear axis scaling, but also logarithmic and logit scaling
# Linear log axis symmetric log axis logit axis
logit_plot()
Copy the code
reference
- Matplotlib.org/stable/tuto…
- Matplotlib.org/stable/gall…
- Matplotlib.org/stable/gall…