1. 2D graphics drawing
1.2 Graph
In “Matplotlib Quick Start”, as an introductory example, we have already learned how to draw curves. For the sake of completeness, in this section, we first briefly review how to use Matplotlib
to draw curves. At the same time, it introduces the drawing of more complex graphs such as multi-curve graphs.
1.2.1 Drawing of simple curves
In the following example, we plot the curve c o s ( x ) cos(x) cos(x), x x x in the interval [ 0 , 2 π ] [0, 2\pi] [0,2π]:
# cos_1.py import math import matplotlib.pyplot as plt scale = range(100) x = [(2 * math.pi * i) / len(scale) for i in scale] y = [math. cos(i) for i in x] plt.plot(x, y) plt. show()
We already know that the data used by Matplotlib
can come from different sources. Next, we will use the data obtained by Numpy
as an example to draw [-10,10]
The curve in the interval y = x 3 + 5 x ? 10 y=x^3 + 5x-10 y=x3 + 5x?10:
#plot_np.py import numpy as np import matplotlib.pyplot as plt x = np.linspace(-10, 10, 800) y = x ** 3 + 5 * x - 10 plt.plot(x, y) plt. show()
1.2.2 Drawing multiple curves
Many times we need to compare multiple sets of data to find the similarities and differences between the data. At this time, we need to draw multiple curves on one picture-multiple curves. The figure below shows the function y = x y=x y drawn in the same picture =x, y = x 2 y=x^2 y=x2, y = l o g e x y=log_ex y=loge?x and y = s i n ( x ) y=sin(x) y=sin(x):
#plot_multi_curve.py import numpy as np import matplotlib.pyplot as plt x = np.linspace(0.1, 2 * np.pi, 100) y_1 = x y_2 = np.square(x) y_3 = np.log(x) y_4 = np. sin(x) plt.plot(x,y_1) plt.plot(x,y_2) plt.plot(x,y_3) plt.plot(x,y_4) plt. show()
Note:
To draw a curve, you need to call plt.plot()
once, but you only need to call plt.show()
once. This delayed rendering mechanism is a key feature of Matplotlib
, we can call the drawing function anywhere in the code, but it will only be rendered when calling plt.show()
Display graphics. In order to better illustrate this delayed rendering mechanism, we write the following code:
# deferred_rendering.py import numpy as np import matplotlib.pyplot as plt def plot_func(x, y): x_s = x[1:] - y[:-1] y_s = y[1:] - x[:-1] plt.plot(x[1:], x_s / y_s) x = np.linspace(-5, 5, 200) y = np. exp(-x ** 2) plt.plot(x, y) plot_func(x, y) plt. show()
It can be seen that although one of the plt.plot()
is called in the plot_func
function, it has no effect on the rendering of the graphics, because plt.plot ()
just declares what we want to render, but doesn’t perform the rendering yet. Therefore, you can use the delayed rendering feature combined with syntax such as for
loop and conditional judgment to complete the drawing of complex graphs, and you can also combine different types of statistical graphs in the same graph.
1.2.3 Read data files and draw graphs
In many cases, the data is stored in the file. Therefore, it is necessary to read the data in the file first, and then draw it. For the sake of explanation, take the .txt
file as an example. Others such as Excel
, CSV files
, etc. can also be read and used for visual drawing. Suppose there is a data.txt
file as follows:
0 1 1 2 2 5 4 17 5 26 6 37
The code for reading data and drawing is as follows:
# read_txt.py import matplotlib.pyplot as plt x, y = [], [] for line in open('data.txt', 'r'): values = [float(s) for s in line. split()] x.append(values[0]) y.append(values[1]) plt.plot(x, y) plt. show()
1.2 Scatter plot
When plotting a graph, we assume a sequential relationship between points. A scatterplot, on the other hand, simply plots points without connections between them. A scatterplot to draw a point for each corresponding pair of data in the two series at the corresponding position in the coordinate axis.
import numpy as np import matplotlib.pyplot as plt data = np.random.rand(1000, 2) plt.scatter(data[:,0], data[:,1]) plt. show()
As you can see, the function plt.scatter()
is called in exactly the same way as plt.plot()
, taking as input parameters the sequence of x and y coordinates of the points, respectively.
1.3 Bar chart
Bar charts have a variety of forms, and common types include single-group bar charts, multi-group bar charts, stacked bar charts, and symmetrical bar charts.
1.3.1 Single group bar chart
Each representation of the bar chart can be drawn as a vertical bar chart or a horizontal bar chart, taking the two drawing methods of a single group of bar charts as an example.
(1) Vertical bar graph
import matplotlib.pyplot as plt data = [10., 20., 5., 15.] plt. bar(range(len(data)), data) plt. show()
The role of the plt.bar()
function is to receive two parameters, including the x
coordinates of each bar and the height of each bar. plt.bar()
can also control the width of the bars in a bar chart by using the optional argument width
:
import matplotlib.pyplot as plt data = [10., 20., 5., 15.] plt. bar(range(len(data)), data, width=0.5) plt. show()
(2) Horizontal bar graph
If you prefer the look of horizontal bars, you can use the plt.barh()
function, which is basically the same as plt.bar()
in terms of usage, but modifies the bar width ( or should be called height in a horizontal bar chart), the parameter height
needs to be used:
import matplotlib.pyplot as plt data = [10., 20., 5., 15.] plt.barh(range(len(data)), data, height=0.5) plt. show()
1.3.2 Multi-group bar chart
We may need multiple sets of bar charts when we need to compare sales volumes for corresponding quarters in different years.
import numpy as np import matplotlib.pyplot as plt data = [[10., 20., 30., 20.],[40., 25., 53., 18.],[6., 22., 52., 19.]] x = np.arange(4) plt.bar(x + 0.00, data[0], color = 'b', width = 0.25) plt.bar(x + 0.25, data[1], color = 'g', width = 0.25) plt.bar(x + 0.50, data[2], color = 'r', width = 0.25) plt. show()
1.3.3 Stacked bar chart
A stacked bar chart can be drawn by using the optional parameter in the plt.bar()
function, the optional parameter bottom< of the
plt.bar()
function /code> allows to specify the starting value of the bar graph.
import matplotlib.pyplot as plt y_1 = [3., 25., 45., 22.] y_2 = [6., 25., 50., 25.] x = range(4) plt. bar(x, y_1, color = 'b') plt. bar(x, y_2, color = 'r', bottom = y_1) plt. show()
This can be combined with a for
loop to stack more bars using the deferred rendering mechanism:
import numpy as np import matplotlib.pyplot as plt data = np.array([[5., 30., 45., 22.], [5., 25., 50., 20.], [1., 2., 1., 1.]]) x = np.arange(data.shape[1]) for i in range(data. shape[0]): plt. bar(x, data[i], bottom = np. sum(data[:i], axis = 0)) plt. show()
1.3.4 Symmetrical bar chart
For example, when we want to plot the number of males versus females in different age groups, a simple and useful technique is to draw two bar charts symmetrically:
import numpy as np import matplotlib.pyplot as plt w_pop = np.array([5., 30., 45., 22.]) m_pop = np.array( [5., 25., 50., 20.]) x = np.arange(4) plt. barh(x, w_pop) plt. barh(x, -m_pop) plt. show()
The bar graph for the female population in the figure is plotted as usual. However, the bars for the bar chart for the male population extend to the left instead of to the right. Negative values of the data can be used to quickly achieve the drawing of symmetrical bar charts.
1.4 Pie chart
Pie charts can be used to compare the relative relationship between quantities. The plt.pie()
function takes a series of values as input, passes the values to Matplolib
, and it automatically calculates The relative area of each value in a pie chart, and plot it:
import matplotlib.pyplot as plt data = [10, 15, 30, 20] plt. pie(data) plt. show()
1.5 Histogram
A histogram is a graphical representation of a probability distribution. In fact, a histogram is just a special kind of bar graph. We can easily use Matplotlib
‘s bar chart function and perform some statistical operations to generate a histogram. However, since the histogram is used very frequently, Matplotlib
provides a more convenient function – plt.hist()
.
What the plt.hist()
function does is: get a sequence of values as input. The range of values will be divided into ranges of equal size (by default, the number is 10
), and then a bar chart will be generated, with a range corresponding to a bar, and the height of a bar is the middle of the corresponding range The number of values for , the number of bins is determined by the optional parameter bins
.
import numpy as np import matplotlib.pyplot as plt x = np.random.randn(1024) plt.hist(x, bins = 20) plt. show()
1.6 Box plot
Box plots allow you to compare distributions of values by conveniently displaying the median, quartiles, maximum, and minimum values for a set of values.
import numpy as np import matplotlib.pyplot as plt data = np.random.randn(200) plt. boxplot(data) plt. show()
Tips: The purpose of the plt.boxplot() function is to obtain a set of values and automatically calculate the mean, median and other statistics.
Box plot description:
- The yellow line in the figure is the median of the distribution.
- The square boxes include 50% of the data from the lower quartile Q1 to the upper quartile Q3.
- The lower quartile of the lower whiskers extends to 1.5 (Q3-Q1).
- The upper box shall extend from the upper quartile to 1.5 (Q3-Q1).
- Values farther from the box-whiskers are marked with circles.
To plot multiple boxplots in a single figure, it is not feasible to call plt.boxplot()
once for each boxplot. It will draw all the boxplots together into one messy, unreadable graph. If you want to achieve the desired effect, you only need to draw multiple boxplots at the same time in one call to plt.boxplot()
, as shown below:
import numpy as np import matplotlib.pyplot as plt data = np.random.randn(200, 6) plt. boxplot(data) plt. show()
2. 3D graphics drawing
The function usage method of drawing 3D
graphics is very similar to that of 2D
. In the last section, we have learned a series of drawing of 2D
graphics, and then Next, we add another dimension to the graph to show more information.
2.1 3D scatter plot
A 3D
scatterplot is drawn in much the same way as a 2D
scatterplot.
import numpy as np from mpl_toolkits.mplot3d import Axes3D import matplotlib.pyplot as plt # Dataset generation a, b, c = 10., 28., 8. / 3. def lorenz_map(x, dt = 1e-2): x_dt = np.array([a * (x[1] - x[0]), x[0] * (b - x[2]) - x[1], x[0] * x[1] - c * x[2]]) return x + dt * x_dt points = np. zeros((2000, 3)) x = np.array([.1, .0, .0]) for i in range(points. shape[0]): points[i], x = x, lorenz_map(x) # Plotting fig = plt. figure() ax = fig.gca(projection = '3d') ax.set_xlabel('X axis') ax.set_ylabel('Y axis') ax.set_zlabel('Z axis') ax.set_title('Lorenz Attractor a=%0.2f b=%0.2f c=%0.2f' % (a, b, c)) ax.scatter(points[:, 0], points[:, 1], points[:, 2], zdir = 'z', c = 'c') plt. show()
It should be noted that in the pop-up interactive drawing window, hold down the left mouse button and move the mouse to rotate and view the 3D graphics.
Next, we explain in detail how to use Matplotlib
for 3D drawing, we first need to import the 3D extension Axes3D
of Matplotlib
:
from mpl_toolkits.mplot3d import Axes3D
For 3D plotting, create a Figure
instance and attach an Axes3D
instance:
fig = plt. figure() ax = fig.gca(projection='3d')
Afterwards, a 3D scatterplot is drawn in exactly the same way as a 2D scatterplot:
ax.scatter(points[:, 0], points[:, 1], points[:, 2], zdir = 'z', c = 'c')
It should be noted that to draw a 3D
scatter plot, you need to call the scatter()
method of the Axes3D
instance, not plt
in the scatter
method. Only the scatter()
method in Axes3D
can interpret 3D data. At the same time, the annotations in the 2D
chart can also be used in the 3D
chart, such as set_title()
, set_xlabel()
, set_ylabel()
and set_zlabel()
etc.
2.2 3D graph
Similar to drawing a scatter plot in the 3D
space, drawing a 3D
curve also needs to set an Axes3D
instance, and then call its plot ()
method:
import numpy as np from mpl_toolkits.mplot3d import Axes3D import matplotlib.pyplot as plt # Dataset generation a, b, c = 10., 28., 8. / 3. def lorenz_map(x, dt = 1e-2): x_dt = np.array([a * (x[1] - x[0]), x[0] * (b - x[2]) - x[1], x[0] * x[1] - c * x[2]]) return x + dt * x_dt points = np. zeros((8000, 3)) x = np.array([.1, .0, .0]) for i in range(points. shape[0]): points[i], x = x, lorenz_map(x) # Plotting fig = plt. figure() ax = fig.gca(projection = '3d') ax.set_xlabel('X axis') ax.set_ylabel('Y axis') ax.set_zlabel('Z axis') ax.set_title('Lorenz Attractor a=%0.2f b=%0.2f c=%0.2f' % (a, b, c)) ax.plot(points[:, 0], points[:, 1], points[:, 2], c = 'c') plt. show()
2.3 3D scalar fields
The 3D
plots we’ve seen so far are similar to the corresponding 2D
plots, but there are also many features specific to 3D plotting, such as plotting a 2D scalar field as 3D
surfaces, the plot_surface()
method displays a scalar field as a three-dimensional surface using the three sequences x x x, y y y, and z z z:
import numpy as np from matplotlib import cm from mpl_toolkits.mplot3d import Axes3D import matplotlib.pyplot as plt x = np.linspace(-3, 3, 256) y = np.linspace(-3, 3, 256) x_grid, y_grid = np. meshgrid(x, y) z = np.sinc(np.sqrt(x_grid ** 2 + y_grid ** 2)) fig = plt. figure() ax = fig.gca(projection = '3d') ax.plot_surface(x_grid, y_grid, z, cmap=cm.viridis) plt. show()
You can see that the lines on the surface have prominent color identification. If you don’t want to see the color of the curve displayed on the 3D surface, you can use the additional optional parameters of plot_surface()
:
ax.plot_surface(x_grid, y_grid, z, cmap=cm.viridis, linewidth=0, antialiased=False)
Similarly, we can also keep only the color of the curve, and the surface does not use other colors, which can also be done through the optional parameters of plot_surface()
:
import numpy as np from matplotlib import cm from mpl_toolkits.mplot3d import Axes3D import matplotlib.pyplot as plt x = np.linspace(-3, 3, 256) y = np.linspace(-3, 3, 256) x_grid, y_grid = np. meshgrid(x, y) z = np.sinc(np.sqrt(x_grid ** 2 + y_grid ** 2)) fig = plt. figure() ax = fig.gca(projection = '3d') ax.plot_surface(x_grid, y_grid, z, edgecolor='b', color='w') plt. show()
And if we want to eliminate the surface and only use the wireframe to draw, we can use the plot_wireframe()
function, the plot_wireframe()
parameter is the same as the plot_surface()
same, use two optional parameters rstride
and cstride
to make Matplotlib
skip the x x x and y y y axes for a specified number of coordinates, use to reduce the density of the curve:
ax.plot_wireframe(x_grid, y_grid, z, cstride=10, rstride=10, color='c')
2.4 Drawing 3D surfaces
In the preceding method, plot_surface()
is used to plot scalars: functions of the form f(x, y)=z
, but Matplotlib
also 3D surfaces can be drawn in a more general way:
import numpy as np from mpl_toolkits.mplot3d import Axes3D import matplotlib.pyplot as plt # Generate torus mesh angle = np.linspace(0, 2 * np.pi, 32) theta, phi = np. meshgrid(angle, angle) r, r_w = .25, 1. x = (r_w + r * np. cos(phi)) * np. cos(theta) y = (r_w + r * np. cos(phi)) * np. sin(theta) z = r * np.sin(phi) # Display the mesh fig = plt. figure() ax = fig.gca(projection = '3d') ax.set_xlim3d(-1, 1) ax.set_ylim3d(-1, 1) ax.set_zlim3d(-1, 1) ax.plot_surface(x, y, z, color = 'c', edgecolor='m', rstride = 2, cstride = 2) plt. show()
It is also possible to replace the call to plot_surface()
with plot_wireframe()
to get a wireframe view of the donut:
ax.plot_wireframe(x, y, z, edgecolor='c', rstride = 2, cstride = 1)
2.5 Draw 2D graphics in 3D coordinate axes
An efficient way to annotate 3D graphics is with 2D graphics:
import numpy as np from mpl_toolkits.mplot3d import Axes3D import matplotlib.pyplot as plt x = np.linspace(-3, 3, 256) y = np.linspace(-3, 3, 256) x_grid, y_grid = np. meshgrid(x, y) z = np.exp(-(x_grid ** 2 + y_grid ** 2)) u = np. exp(-(x ** 2)) fig = plt. figure() ax = fig.gca(projection = '3d') ax.set_zlim3d(0, 3) ax.plot(x, u, zs=3, zdir='y', lw = 2, color = 'm') ax.plot(x, u, zs=-3, zdir='x', lw = 2., color = 'c') ax.plot_surface(x_grid, y_grid, z, color = 'b') plt. show()
Axes3D
The instance also supports common 2D rendering commands, such as plot()
:
ax.plot(x, u, zs=3, zdir='y', lw = 2, color = 'm')
The Axes3D instance’s call to plot()
has two new optional parameters:
zdir
: used to decide which plane to draw 2D drawing on, optional values include x
, y
or z
;
zs
: Used to determine the offset of the plane.
So, to embed 2D graphics into 3D graphics, simply use the 2D primitives for the Axes3D
instance, with the optional parameters, zdir
and zs
, to place the required rendering graphics plane.
Next, let’s see an example of stacking 2D
bar charts in 3D
space in action:
import numpy as np from matplotlib import cm import matplotlib.colors as col from mpl_toolkits.mplot3d import Axes3D import matplotlib.pyplot as plt # Data generation alpha = 1. / np.linspace(1, 8, 5) t = np.linspace(0, 5, 16) t_grid, a_grid = np. meshgrid(t, alpha) data = np. exp(-t_grid * a_grid) # Plotting fig = plt. figure() ax = fig.gca(projection = '3d') cmap = cm.ScalarMappable(col.Normalize(0, len(alpha)), cm.viridis) for i, row in enumerate(data): ax.bar(4 * t, row, zs=i, zdir='y', alpha=0.8, color=cmap.to_rgba(i)) plt. show()
2.6 3D histogram
Finally, let’s introduce the drawing of 3D
histogram.
import numpy as np from matplotlib import cm import matplotlib.colors as col from mpl_toolkits.mplot3d import Axes3D import matplotlib.pyplot as plt # Data generation alpha = np.linspace(1, 8, 5) t = np.linspace(0, 5, 16) t_grid, a_grid = np. meshgrid(t, alpha) data = np. exp(-t_grid * (1. / a_grid)) # Plotting fig = plt. figure() ax = fig.gca(projection = '3d') xi = t_grid. flatten() yi = a_grid. flatten() zi = np.zeros(data.size) dx = .30 * np.ones(data.size) dy = .30 * np.ones(data.size) dz = data. flatten() ax. set_xlabel('T') ax.set_ylabel('Alpha') ax.bar3d(xi, yi, zi, dx, dy, dz, color = 'c') plt. show()
The 3D
bar is positioned in a grid layout, and the bar3d()
method accepts six required parameters as input. The first three parameters are the x
, y
and z
coordinates of the lower end of each cylinder:
xi = t_grid.flatten() yi = a_grid. flatten() zi = np.zeros(data.size)
The bar3d()
method takes as input a list of coordinates, not grid coordinates, so the flatten method needs to be called on the matrices a_grid
and t_grid
. The other three required parameters of the bar3d()
method are the values of each bar in each dimension. Here, the height of the histogram is taken from the data matrix. Bar width and depth set to 0.30
:
dx = .30 * np.ones(data.size) dy = .30 * np.ones(data.size) dz = data. flatten()
Turn: https://blog.csdn.net/LOVEmy134611/article/details/124504526