Table of contents
1. Graphic drawing encyclopedia
1.1.1 Draw single line graphics
1.1.2 Drawing multi-line graphs
1.1.3 Read the data in the file and draw graphics
1.1.5.2 Multiple groups of bar charts
1.2.5 Draw 2D graphics in 3D coordinates
2. Matplotlib drawing style and style
2.2.2 Draw curves using custom colors
2.2.3 Draw a scatter plot using custom colors
2.2.3.1 Use the same color for all points
2.2.3.2 Give each point a different color
2.2.4 Use custom colors for the edges of the scatter plot
2.2.5 Draw bar chart using custom colors
2.2.6 Draw a pie chart using custom colors
2.2.7 Draw box plots using custom colors
2.2.8 Drawing a scatter plot using color mapping
2.2.9 Drawing bar charts using color mapping
2.2.10 Create a custom color scheme
2.3.1 Customize line style and line width
2.3.3.2 Controlling the size of markers
1. Graphic drawing encyclopedia
1.1 2D graphics drawing
1.1.1 Draw single line graphics
Draw a one-line diagram by defining a queue:
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()
Matplotlib
The data used can come from different sources. Next, we take Numpy
the data obtained using as an example to draw [-10,10]
a curve in the interval, as follows:
x = np.linspace(-10, 10, 800)
y = x ** 3 + 5 * x - 10
plt.plot(x, y)
plt.show()
plot()
The usage is as follows:
pythonCopy code plot(x, y, linestyle=None, marker=None, color=None, label=None, **kwargs)
Among them, the meaning of the parameters is as follows:
-
x
: A one-dimensional array or list representing the position of the data point on the X-axis. -
y
: A one-dimensional array or list representing the position of the data point on the Y-axis. -
linestyle
: (optional parameter) String indicating the style of the line. The default value is None, which means the default line style is used. You can specify different line styles, such as solid line ('-'), dashed line ('--'), dotted line ('-.'), dotted line (':'), etc. -
marker
: (optional parameter) A string indicating the marker type of the data point. The default value is None, which means no markers for data points are displayed. You can specify different mark types, such as circles ('o'), squares ('s'), triangles ('^'), etc. -
color
: (optional parameter) A string representing the color of lines and markers. The default value is None, which means the default color is used. You can use color strings such as 'red', 'blue', 'green', etc., or abbreviated color strings such as 'r', 'b', 'g', etc. -
label
: (optional parameter) A string representing the label of the line. The default value is None. You can set this label when you want to add a legend to the drawn lines. -
**kwargs
: (optional parameters) These are some optional keyword parameters used to configure other properties of the line, such as line width, transparency, etc.
You can draw a line using the method by passing the x
sum of data. The parameter is optional, used to control the line style; the parameter is optional, used to display the markers of the data points; the parameter is optional, used to specify the color of the lines and markers; the parameter is optional, used to add the label of the line, used for the legend display .y
plot()
linestyle
marker
color
label
When drawing multiple lines, you can call plot()
the method multiple times, passing different x
sum y
data each time, and set different styles and colors as needed. When plotting multiple lines, you can use label
parameters to add labels to each line and then use plt.legend()
to display the legend.
1.1.2 Drawing multi-line graphs
Many times it is necessary to compare multiple sets of data to find similarities and differences between the data. In this case, it is necessary to draw multiple curves on one picture - a multi-curve graph. The example is as follows:
#绘制多线图
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()
The drawing of a curve needs to be called once plt.plot()
, and plt.show()
only needs to be called once. This deferred rendering mechanism is Matplotlib
a key feature of , we can call drawing functions anywhere in the code, but the plt.show()
display graphics will only be rendered when .
for example:
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()
Even though one of them plt.plot()
is plot_func
called in the function, it has no effect on the rendering of the graph, because it plt.plot()
only declares what we want to render, but does not perform rendering yet. Therefore, you can use the delayed rendering feature combined with for
syntax such as loops and conditional judgments to complete the drawing of complex graphics, and you can also combine different types of statistical charts in the same picture.
1.1.3 Read the data in the file and draw graphics
In many cases, data is stored in files. Therefore, the data in the file needs to be read first and then drawn. For the sake of explanation, files are taken as an example. Others such as , .txt
etc. Excel
can CSV文件
also be read and used for visual drawing.
For example:
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.1.4 Drawing a scatter plot
The scatter method is usually a function provided by a data visualization library (such as Matplotlib or Seaborn) for plotting scatter plots:
Parameters and usage of scatter method in Matplotlib:
matplotlib.pyplot.scatter(x, y, s=None, c=None, marker=None, cmap=None, norm=None, vmin=None, vmax=None, alpha=None, linewidths=None, edgecolors=None)
Parameter explanation:
-
x
: Abscissa data, which is an array or Series used to represent the abscissa position of each point in the scatter plot. -
y
: Vertical coordinate data, which is an array or Series used to represent the vertical coordinate position of each point in the scatter plot. -
s
: The size of the points, which can be a numerical value or an array, controls the size of the scatter points. The default value isNone
, which means use the default point size. -
c
: The color of the point, which can be a color string, color list or array, used to control the color of the scatter points. The default value isNone
, which means use the default color. -
marker
: The mark style of the point, which can be a mark string, for example, 'o' means dot, 's' means square, etc. The default value isNone
, meaning the default markup style is used. -
cmap
: Colormap object or string used to specify color mapping. It is used when specifying the c parameter as a numerical value to map the numerical value to the color space. The default value isNone
, which means use the default color map. -
norm
: Normalize object used to normalize data. It is used when specifying the c parameter as a numeric value. The default value isNone
, which means the default normalization method is used. -
vmin
andvmax
: used to set the minimum and maximum values of the color map range. They are used when specifying the c parameter as a numeric value. The default value isNone
, which means using the minimum and maximum values of the data as the range. -
alpha
: The transparency of the point, the value range is [0, 1], where 0 means completely transparent and 1 means completely opaque. The default value isNone
, which means use the default transparency. -
linewidths
: The width of the point boundary, used to control the width of the boundary line of the point. The default value isNone
, which means the default line width is used. -
edgecolors
: The color of the point boundary, used to control the color of the boundary line of the point. The default value isNone
, which means use the default color.
data = np.random.rand(1000, 2) #1000行、2列的随机数数组,符合均匀分布
plt.scatter(data[:,0], data[:,1])
plt.show()
1.1.5 Drawing a bar chart
Bar charts have rich forms of expression. Common types include single group bar charts, multiple groups of bar charts, stacked bar charts, symmetrical bar charts, etc.
1.1.5.1 Single Bar Chart
Each representation of a bar chart can be plotted as a vertical bar chart or a horizontal bar chart.
1. Vertical bar chart
plt.bar
Is the method in the Matplotlib library used to draw bar charts. It displays data in the form of bars, which is great for showing comparisons between different categories or groups.
The general syntax used plt.bar
is as follows:
pythonCopy code plt.bar(x, height, width=0.8, align='center', **kwargs)
Among them, the meaning of the parameters is as follows:
-
x
: This is an iterable object, usually a list or array, that specifies the abscissa position of the bar chart. Each element represents the abscissa position of a bar. -
height
: This is an iterable object, usually a list or array, that specifies the height or length of the bar chart. Each element represents the height of a bar. -
width
: (optional) This is a scalar or iterable specifying the width of the bar. The default value is 0.8, which means each bar is 0.8 units wide. If you want to customize the width of each bar, you can pass a scalar value or an iterable with the same length asx
and .height
-
align
: (optional parameter) This is a string that specifies the alignment of the bars. The default value is'center'
, which means the bars are centered on the abscissa. Other possible values include'edge'
aligning the bars with the left edge of the abscissa, or'align'
aligning the bars with the right edge of the abscissa. -
**kwargs
: (optional parameters) These are some optional keyword parameters used to configure other properties of the bar chart, such as color, label, transparency, etc. For example, you can usecolor
parameters to specify the color of the bars,label
parameters to add labels to the bars, etc.
Once called plt.bar
to draw a bar chart, you can use methods such as plt.xlabel
, plt.ylabel
, plt.title
and to add axis labels and plot titles, as well as other Matplotlib methods to beautify the graph.
data = [10., 20., 5., 15.]
plt.bar(range(len(data)), data, width=0.5)
plt.show()
2. Horizontal bar chart
If you prefer the appearance of horizontal bars, you can use plt.barh()
the function, which is basically the same as in usage plt.bar()
, but to modify the bar width (or height in horizontal bar charts), you need to use parameters height
:
Here is plt.barh()
the general syntax for methods:
plt.barh(y, width, height=0.8, left=None, **kwargs)
Among them, the meaning of the parameters is as follows:
-
y
: This is an iterable object, usually a list or array, that specifies the vertical coordinate position of the bar chart. Each element represents the ordinate position of a bar. -
width
: This is an iterable object, usually a list or array, that specifies the width or length of the bar chart. Each element represents the width of a bar. -
height
: (optional) This is a scalar or iterable specifying the height of the bar. The default value is 0.8, which means each bar is 0.8 units tall. If you want to customize the height of each bar, you can pass a scalar value or an iterable with the same length asy
and .width
-
left
: (optional) This is a scalar or an iterable that specifies the starting value for the bars. The default value is None, which means each bar starts at 0. If you want to achieve a stacking effect, you canleft
specify the starting value of each bar through parameters. -
**kwargs
: (optional parameters) These are some optional keyword parameters used to configure other properties of the bar chart, such as color, label, transparency, etc.
data = [10., 20., 5., 15.]
plt.barh(range(len(data)), data, height=0.5)
plt.show()
1.1.5.2 Multiple groups of bar charts
When comparisons occur, multiple sets of bar charts can be drawn:
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()
In the same way, use the barh method to draw multiple sets of horizontal bar charts:
data = [[10., 20., 30., 20.],[40., 25., 53., 18.],[6., 22., 52., 19.]]
x = np.arange(4)
plt.barh(x + 0.00, data[0], color = 'b', height = 0.25)
plt.barh(x + 0.25, data[1], color = 'g', height = 0.25)
plt.barh(x + 0.50, data[2], color = 'r', height = 0.25)
plt.show()
1.1.5.3 Stacked Bar Chart
plt.bar()
A stacked bar chart can be plotted using an optional parameter in plt.bar()
the function that bottom
allows you to specify a starting value for the bar chart.
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()
If you want to draw a horizontal stacked bar chart, you need to use left to specify the actual position:
y_1 = [3., 25., 45., 22.]
y_2 = [6., 25., 50., 25.]
x = range(4)
# # 对y_1和y_2进行累加
# y_1_cumsum = np.cumsum(y_1)
# y_2_cumsum = np.cumsum(y_2)
plt.barh(x, y_1, color='b', label='y_1')
plt.barh(x, y_2, color='r', left=y_1, label='y_2')
plt.legend()
plt.show()
This can be combined with for
a loop to stack more bars using a delayed rendering mechanism:
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.1.5.4 Symmetrical Bar Chart
When we want to plot the number of males compared to females in different age groups, a simple and useful trick is to plot two bar graphs symmetrically:
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()
1.1.4 Pie chart
Pie charts can be used to compare the relative relationships between quantities. plt.pie()
The function takes a series of values as input and passes the values to Matplolib
, and it will automatically calculate the relative area of each value in the pie chart and draw it:
The general syntax used plt.pie()
is as follows:
pythonCopy code
plt.pie(x, explode=None, labels=None, colors=None, autopct=None, shadow=False, startangle=0, **kwargs)
Among them, the meaning of the parameters is as follows:
-
x
: This is a 1-dimensional array or list representing the data values of each part. These data values are used to calculate the proportions of each part and draw the pie chart. -
explode
: (optional parameter) This is a 1-dimensional array or list that specifies whether certain parts should be separated from the pie chart. The default value is None, which means no separation is performed. If you want to separate some parts, you can pass anx
array of the same length, where a value greater than 0 represents the distance of separation. -
labels
: (optional parameter) This is a 1D array or list specifying the labels for each section in the pie chart. The default value is None, which means no label is displayed. If you want to display labels, you can pass anx
array of the same length containing the label text for each section. -
colors
: (optional parameter) This is a 1-dimensional array or list that specifies the color of each section in the pie chart. The default value is None, which means the default color cycle is used. If you want to customize the colors, you can pass anx
array of the same length containing the colors for the individual parts. -
autopct
: (optional parameter) This is a string or function that displays the percentage of each part. The default value is None, which means no percentage is displayed. If you pass a string, for example'%1.1f%%'
, a percentage to one decimal place will be displayed. If passed a function, the function will receive a numeric value as argument and return a string used to display the percentage. -
shadow
: (optional parameter) This is a Boolean value that specifies whether to add a shadow below the pie chart. The default value is False, which means no shadow is added. -
startangle
: (optional parameter) This is a scalar that specifies the starting angle of the pie chart. The default value is 0, which means the pie chart is drawn starting from an angle of 0 degrees, in a counterclockwise direction. -
**kwargs
: (optional parameters) These are some optional keyword parameters used to configure other properties of the pie chart, such as border line width, border line color, etc.
Once called plt.pie()
to draw a pie chart, you can use plt.axis('equal')
to ensure that the pie chart is circular and use plt.legend()
to display the legend.
data = [10, 15, 30, 20]
plt.pie(data,explode = [0.1,0.1,0.1,0.1],shadow=True)
plt.show()
1.1.5 Histogram
A histogram is a graphical representation of a probability distribution. In fact, a histogram is just a special kind of bar chart. We can easily use Matplotlib
the barplot function of and do some statistical operations to generate a histogram. However, given that histograms are used very frequently, Matplotlib
a more convenient function is provided - plt.hist()
. plt.hist()
The function is to take a series of values as input. The range of values will be divided into equal-sized ranges (the number is by default 10
), and then a bar chart will be generated. A range corresponds to a bar. The height of a bar is the number of values in the corresponding range. The height of the bar is The quantity is determined by optional parameters bins
.
The general syntax used plt.hist()
is as follows:
pythonCopy code
plt.hist(x, bins=None, range=None, density=False, cumulative=False, color=None, edgecolor=None, **kwargs)
Among them, the meaning of the parameters is as follows:
-
x
: This is a 1-dimensional array or list representing the data to be histogram plotted. -
bins
: (optional parameter) This is an integer or an array specifying bins, used to control the number and position of bins in the histogram. The default value is None, which means the automatically selected number of boxes is used. You can pass an integer value to specify the number of boxes, or an array to specify specific box boundaries. -
range
: (optional parameter) This is a tuple or list specifying the data range for the histogram. The default value is None, which means the entire range of data is used. You can pass a tuple or list, such as(min_value, max_value)
, to limit the range of data displayed by the histogram. -
density
: (optional parameter) A Boolean value that specifies whether the histogram is normalized. The default value is False, which means that the histogram displays the frequency of the original data. If set to True, the histogram will display relative frequencies such that the histogram areas sum to 1. -
cumulative
: (optional parameter) A Boolean value that specifies whether to plot a cumulative histogram. The default value is False, which means drawing the original histogram. If set to True, a cumulative histogram will be plotted, showing the cumulative amount of data within each bin. -
color
: (optional parameter) This is a string or color code that specifies the fill color of the histogram. -
edgecolor
: (optional parameter) This is a string or color code that specifies the histogram boundary line color. -
**kwargs
: (optional parameters) These are some optional keyword parameters used to configure other properties of the histogram, such as transparency, labels, etc.
Once called plt.hist()
to draw a histogram, you can add axis labels and plot titles using methods such as plt.xlabel()
, plt.ylabel()
and , and display a legend using ,plt.title()
plt.legend()
data1 = np.random.rand(1024)
plt.hist(data1, bins=10, alpha=0.6, label='Data 1', histtype='bar', rwidth=0.8)
plt.xlabel('Value')
plt.ylabel('Frequency')
plt.title('Histogram with Gap between Bars')
plt.legend()
plt.show()
If you want to plot multiple histograms with spacing between them, you can use plt.hist()
the method's histtype
parameters. histtype
Parameters are used to specify the type of histogram, including 'bar' (default), 'barstacked', 'step', etc.
For plotting multiple histograms and wanting to have spacing between them, you can choose to use the 'bar' or 'barstacked' type and set the alpha
parameter to a value less than 1, making the histograms transparent and thus showing the spacing. Effect.
In the above code, the histtype='bar'
and alpha=0.6
parameters are used to set the histogram type to 'bar' and make the histograms spaced. At the same time, we also set up rwidth=0.8
to control the width of the histogram so that the histogram has spacing in the horizontal direction.
1.1.6 Box plot
The boxplot will show a five-number summary of the data: minimum value, lower quartile, median, upper quartile, maximum value, and possible outliers.
The general syntax used plt.boxplot(data)
is as follows:
plt.boxplot(data, notch=None, sym=None, vert=None, whis=None, positions=None, widths=None, patch_artist=None, **kwargs)
Among them, the meaning of the parameters is as follows:
-
data
: This is a list, array, or combination of lists/arrays representing the data set to be plotted as a boxplot. You can pass a list or array, or a combination of multiple lists or arrays to draw multiple boxplots in the same figure. -
notch
: (optional parameter) This is a Boolean value that specifies whether to draw gaps in the boxplot. The default value is None, which means no gaps are drawn. If set to True, the boxplot will be notched to help show the confidence interval of the data set. -
sym
: (optional parameter) This is a string that specifies how outliers are represented. The default value is None, which means using '+' to indicate outliers. You can pass additional symbols or an empty string to customize the representation of outliers. -
vert
: (optional parameter) This is a Boolean value that specifies the direction of the boxplot. The default value is None, which means drawing a vertical box plot. If set to False, a horizontal boxplot will be drawn. -
whis
: (optional) This is a scalar or tuple specifying the length of the whiskers in the boxplot. The default value is None, which means the default value of 1.5 is used. You can pass a scalar value or a tuple(lower, upper)
to customize the length of the whiskers. -
positions
: (optional argument) This is a scalar or list specifying the position of the boxplot. The default value is None, which means each data set is evenly distributed on the x-axis. You can pass a scalar value or a list with the same number of data sets to customize the position of the boxplot. -
widths
: (optional argument) This is a scalar or list specifying the width of the boxplot. The default value is None, which means use the default width. You can pass a scalar value or a list with the same number of data sets to customize the width of the boxplot. -
patch_artist
: (optional) A Boolean value that specifies whether to use a fill color for the boxplot's box. The default value is None, which means no fill color is used. If set to True, the box of the boxplot will be filled, andboxprops
the fill color and other properties can be specified through parameters. -
**kwargs
: (optional parameters) These are some optional keyword parameters used to configure other properties of the boxplot, such as line color, line style, etc.
Once called plt.boxplot(data)
to draw a box plot, you can use methods such as plt.xlabel()
, plt.ylabel()
and plt.title()
to add axis labels and plot titles, plt.xticks()
and plt.yticks()
to customize tick labels using
Example:
data = np.random.randn(100)
# 绘制箱线图
plt.boxplot(data)
# 添加标题和标签
plt.title('Box Plot Example')
plt.ylabel('Value')
# 显示箱线图
plt.show()
-
The yellow line in the figure is the median of the distribution.
-
The square boxes include the 50% of the data from the lower quartile Q1 to the upper quartile Q3.
-
The lower quartile of the lower box whisker extends to 1.5 (Q3-Q1).
-
The upper box must extend from the upper quartile to 1.5 (Q3-Q1).
-
Values further from the box whiskers are marked with circles.
To plot multiple boxplots in a single graph, it is not feasible to call each boxplot once plt.boxplot()
. It will draw all the boxes together into a confusing, unreadable graphic. If you want to achieve the desired effect, you only need to plt.boxplot()
draw multiple box plots at the same time in one call, as shown below:
data = np.random.randn(200, 6)
#绘制图形
plt.boxplot(data)
# 添加标题和标签
plt.title('Box Plot Example')
plt.ylabel('Value')
# 显示箱线图
plt.show()
1.2 3D graphics drawing
Import:
from mpl_toolkits.mplot3d import Axes3D
1.2.1 3D scatter plot
3D
The drawing method of scatter plot 2D
is basically the same as that of scatter plot. The example is as follows:
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.add_subplot(111, projection='3d') # 使用add_subplot()方法创建三维坐标轴
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()
In Matplotlib, scatter()
methods are used to draw scatter plots on three-dimensional axes. It can represent a series of data points in a three-dimensional space in the form of scatter points.
scatter()
The syntax of the method is as follows:
scatter(x, y, z, c=None, s=None, marker=None, cmap=None, **kwargs)
Among them, the meaning of the parameters is as follows:
-
x
: This is a 1-dimensional array or list representing the position of the scatter plot on the X-axis. -
y
: This is a 1-dimensional array or list representing the position of the scatter plot on the Y-axis. -
z
: This is a 1-dimensional array or list that represents the position of the scatter plot on the Z axis, that is, perpendicular to the XY plane. -
c
: (optional parameter) This is a 1D array or list specifying the color of each scatter point. The default value is None, which means the default color map is used. You can pass an array of the same length asx
,y
and , where each element represents the color of the corresponding scatter point.z
-
s
: (optional argument) This is a scalar or 1D array or list specifying the size of the scatter points. The default value is None, which means the default point size is used. If you pass a scalar value, all scatter points will be the same size. If you pass an array with the same length asx
,y
andz
, each element represents the size of the corresponding scatter point. -
marker
: (optional parameter) This is a string that specifies the marker type for scatter points. The default value is None, which means use circle markers. Other token types can be passed, such as 's', 'o', '^', etc. -
cmap
: (optional parameter) This is a Colormap object or string used to specify the color map. The default value is None, which means the default color map is used. You can pass a Colormap object, or use strings to specify common colormaps, such as 'viridis', 'plasma', 'jet', etc. -
zdir
isscatter()
an optional parameter in the method, used to specify the projection direction of the scatter points on the three-dimensional coordinate axis. It is used to control how scatter points are displayed in three-dimensional space.In
scatter()
the method,zdir
three values can be taken: 'x', 'y' and 'z'. These values represent projections showing scatter points on the X, Y, and Z axes respectively.When
zdir
set to 'x', the projection of the scatter points onto the XY plane will be displayed on the X axis. Whenzdir
set to 'y', the projection of the scatter points on the XZ plane will be displayed on the Y axis. Whenzdir
set to 'z', the projection of the scatter points on the XY plane will be displayed on the Z axis.By default,
zdir
the value is None, in which case the scatter points will be displayed on the XY plane without projection on the X, Y or Z axis. -
**kwargs
: (optional parameters) These are some optional keyword parameters used to configure other properties of the scatter plot, such as transparency, edge color, etc.
scatter()
The method can be called on a three-dimensional axis object ax.scatter()
to draw a three-dimensional scatter plot in the form of. When calling scatter()
, pass data to x
the , y
and z
parameters, and then you can use c
the and s
parameters to specify the color and size, marker
the parameters to specify the marker type, cmap
the parameters to specify the color map, etc.
Steps to draw 3D graphics:
1. First, you need to import Matplotlib
the 3D extension Axes3D
:
from mpl_toolkits.mplot3d import Axes3D
2. For three-dimensional drawing, you need to create an Figure
instance and attach an Axes3D
instance:
fig = plt.figure()
ax = fig.gca(projection='3d')
The gca method can no longer be used. You can use the add_subplot method:
ax = fig.add_subplot(111, projection='3d') # 使用add_subplot()方法创建三维坐标轴
3. Then bring in the corresponding method. Here, scatter is brought in to draw a scatter plot:
ax.scatter(points[:, 0], points[:, 1],points[:, 2], zdir = 'z', c = 'c')
1.2.2 3D curve graph
Similar to 3D
drawing a scatter plot in space, drawing 3D
a curve chart also requires setting up an Axes3D
instance and then calling its plot()
method:
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.add_subplot(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()
1.2.3 3D scalar field
3D
The drawing method is similar to the corresponding 2D
drawing method, but there are also many unique three-dimensional drawing functions, such as drawing a two-dimensional scalar field as a 3D
surface. plot_surface()
The method uses three sequences of x, y and z to display the scalar field as a three-dimensional surface (displaying a two-dimensional the shape of a quantity in three dimensions):
x = np.linspace(-3, 3, 256)
y = np.linspace(-3, 3, 256)
x_grid, y_grid = np.meshgrid(x, y) #使用`np.meshgrid()`方法将一维数组`x`和`y`转换为二维数组,得到`x_grid`和`y_grid`,用于表示XY平面上的点坐标网格。
print(x_grid)
z = np.sinc(np.sqrt(x_grid ** 2 + y_grid ** 2))
fig = plt.figure()
ax = fig.add_subplot(projection = '3d') #创建一个三维坐标轴对象。
ax.plot_surface(x_grid, y_grid, z, cmap=cm.viridis) #x_grid和y_grid表示XY平面上的点坐标网格,z表示每个点上的函数值。cmap=cm.viridis指定使用'viridis'颜色映射,用于在三维图上表示高度的颜色。
plt.show()
plot_surface()
The usage is as follows:
pythonCopy code
plot_surface(X, Y, Z, cmap=None, rstride=1, cstride=1, alpha=1.0, antialiased=False, **kwargs)
Among them, the meaning of the parameters is as follows:
-
X
: A two-dimensional array representing the coordinates of the data on the X-axis. Its shape should beZ
the same as the shape of . -
Y
: A two-dimensional array representing the coordinates of the data on the Y-axis. Its shape should beZ
the same as the shape of . -
Z
: A two-dimensional array, representing the height or value of data in three-dimensional space. Its shape should be the same as the shape ofX
andY
. -
cmap
: Colormap object or string, used to specify color mapping. The default value is None, which means the default color map is used. You can pass a Colormap object, or use strings to specify common colormaps, such as 'viridis', 'plasma', 'jet', etc. -
rstride
: Integer, indicating the step size of sampling in the Z direction. The default value is 1, which means no sampling is performed. Larger values result in fewer points being drawn, making drawing faster, but may affect how detailed the image is. -
cstride
: Integer, indicating the step size of sampling on the XY plane. The default value is 1, which means no sampling is performed. Larger values result in fewer points being drawn, making drawing faster, but may affect how detailed the image is. -
alpha
: Floating point number representing the transparency of the surface. The default value is 1.0, which means opaque. The value range is 0.0 to 1.0, where 0.0 means completely transparent and 1.0 means completely opaque. -
antialiased
: Boolean value indicating whether to use anti-aliasing. The default value is False, which means no anti-aliasing is used. If set to True, the image will be smoother but may increase drawing time. -
color.
When drawing a 3D surface plot, the surface is made up of many small triangles or polygons, and the edge lines between these small shapes are usually the default color. By setting
edgecolor
parameters, you can control the color of these edge lines to be different from the color of the surface, thereby increasing the visualization effect of the graph.edgecolor
Can accept a string or RGB tuple of color values. Commonly used color value strings are as follows:-
'b': blue
-
'g': green
-
'r': red
-
'c': cyan (blue-green)
-
'm': magenta (magenta)
-
'y': yellow
-
'k': black
-
'w': white
You can also pass an RGB tuple, for example
(0.1, 0.2, 0.3)
, representing the RGB color components with values between 0 and 1. This way you can customize the color of the edge lines. -
-
**kwargs
: Optional keyword parameters used to configure other properties of the surface plot, such as line color, line style, etc.
X
, Y
and Z
respectively represent the grid coordinates and height of the data in three-dimensional space, and cmap
the parameters can be used to adjust the color of the surface. rstride
and cstride
parameters are used to control the sampling step size in the Z direction and XY plane, which can be used to optimize drawing speed and image fineness. alpha
The parameter controls the transparency of the surface, and antialiased
the parameter specifies whether to use anti-aliasing.
If you do not want to see the curve color displayed on the 3D surface, you can use plot_surface()
the additional optional parameters of :
ax.plot_surface(x_grid, y_grid, z, cmap=cm.viridis, linewidth=0, antialiased=False)
Example:
x = np.linspace(-3, 3, 256)
y = np.linspace(-3, 3, 256)
x_grid, y_grid = np.meshgrid(x, y) #使用`np.meshgrid()`方法将一维数组`x`和`y`转换为二维数组,得到`x_grid`和`y_grid`,用于表示XY平面上的点坐标网格。
z = np.sinc(np.sqrt(x_grid ** 2 + y_grid ** 2))
fig = plt.figure()
ax = fig.add_subplot(projection = '3d') #创建一个三维坐标轴对象。
ax.plot_surface(x_grid, y_grid, z, cmap=cm.viridis, linewidth=0, antialiased=False) #x_grid和y_grid表示XY平面上的点坐标网格,z表示每个点上的函数值。cmap=cm.viridis指定使用'viridis'颜色映射,用于在三维图上表示高度的颜色。
plt.show()
It is possible to keep only the curve color and use no other colors for the surface, this can also be plot_surface()
done via the optional argument of :
x = np.linspace(-3, 3, 256)
y = np.linspace(-3, 3, 256)
x_grid, y_grid = np.meshgrid(x, y) #使用`np.meshgrid()`方法将一维数组`x`和`y`转换为二维数组,得到`x_grid`和`y_grid`,用于表示XY平面上的点坐标网格。
z = np.sinc(np.sqrt(x_grid ** 2 + y_grid ** 2))
fig = plt.figure()
ax = fig.add_subplot(projection = '3d') #创建一个三维坐标轴对象。
ax.plot_surface(x_grid, y_grid, z, edgecolor='b',color='w') #x_grid和y_grid表示XY平面上的点坐标网格,z表示每个点上的函数值。cmap=cm.viridis指定使用'viridis'颜色映射,用于在三维图上表示高度的颜色。
plt.show()
If you wish to eliminate the surface and draw only the wireframe, you can use plot_wireframe()
the function plot_wireframe()
with the same parameters as plot_surface()
with two optional parameters rstride
and cstride
to make Matplotlib
skip a specified number of coordinates on the x and y axes, used to reduce the density of the curve:
ax.plot_wireframe(x_grid, y_grid, z, cstride=10, rstride=10,color='c')
Example:
plot_wireframe()
The usage is as follows:
plot_wireframe(X, Y, Z, rstride=1, cstride=1, color=None, linewidth=1, antialiased=False, **kwargs)
Among them, the meaning of the parameters is as follows:
-
X
: A two-dimensional array representing the coordinates of the data on the X-axis. Its shape should beZ
the same as the shape of . -
Y
: A two-dimensional array representing the coordinates of the data on the Y-axis. Its shape should beZ
the same as the shape of . -
Z
: A two-dimensional array, representing the height or value of data in three-dimensional space. Its shape should be the same as the shape ofX
andY
. -
rstride
: Integer, indicating the step size of sampling in the Z direction. The default value is 1, which means no sampling is performed. Larger values result in fewer points being drawn, making drawing faster, but may affect how detailed the image is. -
cstride
: Integer, indicating the step size of sampling on the XY plane. The default value is 1, which means no sampling is performed. Larger values result in fewer points being drawn, making drawing faster, but may affect how detailed the image is. -
color
: Color or color sequence used to specify the color of the wireframe. The default value is None, which means the default color is used. -
linewidth
: Floating point number, indicating the width of the wireframe. The default value is 1. -
antialiased
: Boolean value indicating whether to use anti-aliasing. The default value is False, which means no anti-aliasing is used. If set to True, the wireframe will be smoother, but may increase drawing time. -
**kwargs
: Optional keyword parameters used to configure other properties of the wireframe, such as line style, etc.
X
, Y
and Z
respectively represent the grid coordinates and height of the data in the three-dimensional space. The rstride
and cstride
parameters are used to control the sampling step in the Z direction and XY plane, which can be used to optimize the drawing speed and image fineness. color
Parameters are used to specify the color of the wireframe, linewidth
parameters are used to adjust the width of the wireframe, and antialiased
parameters are used to specify whether to use anti-aliasing.
1.2.4 Drawing 3D surfaces
Matplotlib
It is also possible to draw 3D surfaces in a more general way:
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.add_subplot(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()
You can also use to plot_wireframe()
replace the call to plot_surface()
in order to get a wireframe view of the ring:
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.add_subplot(projection = '3d')
ax.set_xlim3d(-1, 1)
ax.set_ylim3d(-1, 1)
ax.set_zlim3d(-1, 1)
ax.plot_wireframe(x, y, z, edgecolor='c', rstride = 2, cstride = 1)
plt.show()
1.2.5 Draw 2D graphics in 3D coordinates
Axes3D
The instance also supports commonly used 2D rendering commands, such as plot()
:
ax.plot(x, u, zs=3, zdir='y', lw = 2, color = 'm')
This code uses ax.plot()
methods to draw a line in a three-dimensional axes.
-
x
: A one-dimensional array or list representing the position of the data point on the X-axis. -
u
: A one-dimensional array or list representing the position of the data point on the Y-axis. -
zs
: Number or one-dimensional array, representing the position of the data point on the Z-axis. In this example,zs=3
it means that the positions of the data points on the Z axis are all 3, which means that all points of this line are on the Z=3 plane. If you pass a one-dimensional array, it represents the position of each data point on the Z axis. -
zdir
: String indicating the projection direction. This parameter is used to control the display direction of this line in three-dimensional space. In this example,zdir='y'
it means that the projection of this line on the XY plane will be displayed on the Y axis. -
lw
: (optional parameter) Number indicating the width of the line. The default value is 2. -
color
: (optional parameter) String indicating the color of the line. The default value is 'm', which means the line color is magenta (magenta). You can use color strings such as 'red', 'blue', 'green', etc., or abbreviated color strings such as 'r', 'b', 'g', etc.
The call to Axes3D instance plot()
has two new optional parameters: zdir
: Used to determine on which plane to draw the 2D drawing, optional values include x
, y
or z
; zs
: Used to determine the offset of the plane. Therefore, to embed a 2D graphic into a 3D graphic, simply use the 2D primitive for Axes3D
the instance, using the optional parameters, zdir
and zs
, to place the desired rendering graphics plane.
Example:
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.add_subplot(projection = '3d')
ax.set_zlim3d(0, 3)#ax.set_zlim3d()是Matplotlib中用于设置三维坐标轴的Z轴范围(限制)的方法。它用于限定Z轴的取值范围,从而控制绘图中Z轴显示的范围。set_zlim3d(zmin, zmax)
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()
In addition to this, bars can 3D
be stacked in space 2D
:
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.add_subplot(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()
-
col.Normalize(0, len(alpha))
: This is the operation of creating a normalize object.col
Ismatplotlib.colors
an alias for a module used to access color-related functions.Normalize(0, len(alpha))
Represents mapping data tolen(alpha)
a range between 0 and. This operation is typically used to normalize data to a specific range for subsequent color mapping. -
cm.viridis
: This specifies the color map to use.cm
Ismatplotlib.cm
an alias for the module used to access the color mapping functionality.viridis
Is a predefined color map that contains a series of colors that vary from low values (such as 0) to high values (such as 1), used to represent the height or other properties of data in a plot. -
cm.ScalarMappable(col.Normalize(0, len(alpha)), cm.viridis)
: This operation combines the previously created normalization object and color map object to generate a scalar map object that can be mapped to a color. This object is used in drawing to map numerical values to corresponding colors. -
ax.bar(4 * t, row, zs=i, zdir='y', alpha=0.8, color=cmap.to_rgba(i))
: Draw a bar in the three-dimensional coordinate axis,4 * t
indicating the X coordinate of the bar,row
indicating the height of the bar,zs=i
indicating the Z coordinate of the bar,zdir='y'
indicating that the projection of the bar on the XY plane will be displayed on the Y axis,alpha=0.8
indicating the bar The transparency is 0.8,color=cmap.to_rgba(i)
indicating that the color of the bar is obtainedi
through the color map objectcmap
1.2.6 3D Column Chart
3D
The cylinder is positioned in a grid layout. bar3d()
The method accepts six required parameters as input and bar3d()
is the method used in Matplotlib to draw three-dimensional bar charts. It can draw one or more bars in a three-dimensional coordinate axis for visualizing three-dimensional data.
bar3d()
The usage is as follows:
bar3d(x, y, z, dx, dy, dz, color='b', zsort='average', *args, **kwargs)
Among them, the meaning of the parameters is as follows:
-
x
: A one-dimensional array or list representing the position of the center point of each bar on the X-axis. -
y
: A one-dimensional array or list representing the position of the center point of each bar on the Y-axis. -
z
: One-dimensional array or list, indicating the position of the center point of each bar on the Z axis, that is, the height of the bar. -
dx
: A one-dimensional array or list representing the width of each bar in the X-axis direction. -
dy
: A one-dimensional array or list representing the width of each bar in the Y-axis direction. -
dz
: One-dimensional array or list, indicating the height of each bar in the Z-axis direction, that is, the thickness of the bar. -
color
: (optional parameter) A string or color sequence indicating the color of the bar. The default value is blue ('b'). -
zsort
: (optional parameter) A string indicating the drawing order of the bars. The default value is 'average', which means to sort the bars according to the average value of the Z-axis coordinate. You can also choose 'min' to sort by the minimum value of the Z-axis coordinate, 'max' to sort by the maximum value of the Z-axis coordinate, or 'none' to not sort. -
*args
and**kwargs
: (optional parameters) These are some additional positional parameters and keyword parameters used to configure other properties of the bar, such as line color, line style, etc.
You can use the method to draw one or more three-dimensional bars by passing data for x
, y
and , and width and height data for , and . The center point of each bar is specified by , and , the width is specified by and , and the height is specified by .z
dx
dy
dz
bar3d()
x
y
z
dx
dy
dz
color
The parameter is used to set the color of the bar. You can pass color strings, such as 'red', 'blue', 'green', etc., or you can use abbreviated color strings, such as 'r', 'b', 'g', etc. , or use a color sequence.
zsort
Parameters are used to control the drawing order of the bars. The bars can be sorted according to the average, minimum or maximum value of the Z-axis coordinate, or not sorted.
Example:
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.add_subplot(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()
2. Matplotlib drawing style and style
2.1 matplotlib style
In order to meet different application needs, Matplotlib
it contains 28
different styles. When drawing, you can choose different drawing styles according to your needs. Use the following code to get Matplotlib
all available styles in :
import matplotlib as mpl
from matplotlib import pyplot as plt
# 查看 Matplotlib 可用绘图风格
print(plt.style.available
plt.style.use("style")
The default drawing style can be modified using , where style
is Matplolib
the style available in :
# 设置默认绘图风格为 seaborn-darkgrid
plt.style.use("seaborn-darkgrid")
x = np.linspace(0, 2 * np.pi, 100)
y = np.cos(x)
plt.plot(x, y)
plt.show()
In addition, Maplotlib
there are some very interesting styles in , such as hand-drawn style:
# 启用手绘风格
plt.xkcd()
x = np.linspace(0, 2 * np.pi, 100)
y = np.cos(x)
plt.plot(x, y)
plt.show()
There are also hand-drawn style bar charts:
#Enable hand-drawn style
plt.xkcd()
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()
2.2 Custom colors
2.2.1 Custom colors
Matplotlib
There are many ways to define colors in , common methods include:
-
Triplet (
Triplets
): Color can be described as a real triplet, that is, the red, blue, and green components of the color, where each component is in the[0,1]
interval. Therefore,(1.0, 0.0, 0.0)
represents pure red,(1.0, 0.0, 1.0)
while represents pink. -
Quadruple (
Quadruplets
): Their first three elements are defined the same as the triple, and the fourth element defines the transparency value. This value is also[0,1]
within the range. When rendering graphics into a picture file, using transparent colors allows the drawn graphics to blend with the background. -
Predefined names: Interpret
Matplotlib
standardHTML
color names as actual colors. For example, the stringred
can be represented as red. At the same time, some colors have concise aliases, as shown in the following table: -
4. HTML 颜色字符串:
Matplotlib 可以将
HTML 颜色字符串解释为实际颜色。这些字符串被定义为
#RRGGBB ,其中
RR 、
GG 和
BB` are the red, green and blue components using hexadecimal encoding respectively.
5. Grayscale string: Matplotlib
Interpret the string representation of a floating point value as grayscale, for example, 0.75
represents medium light gray.
2.2.2 Draw curves using custom colors
By setting plt.plot()
the parameters of the function color
(or the equivalent abbreviation is c
), you can set the color of the curve, example:
def pdf(x, mu, sigma):
a = 1. / (sigma * np.sqrt(2. * np.pi))
b = -1. / (2. * sigma ** 2)
return a * np.exp(b * (x - mu) ** 2)
x = np.linspace(-6, 6, 1000)
for i in range(5):
samples = np.random.standard_normal(50)
mu, sigma = np.mean(samples), np.std(samples)
plt.plot(x, pdf(x, mu, sigma), color = str(.15*(i+1)))
plt.plot(x, pdf(x, 0., 1.), color = 'k')
plt.plot(x, pdf(x, 0.2, 1.), color = '#00ff00')
plt.plot(x, pdf(x, 0.4, 1.), color = (0.9,0.9,0.0))
plt.plot(x, pdf(x, 0.4, 1.), color = (0.9,0.9,0.0,0.8))
plt.show()
2.2.3 Draw a scatter plot using custom colors
The color of the scatter plot can be controlled in the same way as the curve plot, and there are two forms available:
-
Use the same color for all points: All points will appear in the same color.
-
Define a different color for each point: Provides a different color for each point.
2.2.3.1 Use the same color for all points
Take two sets of points drawn from a binary Gaussian distribution y_1
and y_2
, with the points in each set having the same color:
y_1 = np.random.standard_normal((150, 2)) #标准正太分布
y_1 += np.array((-1, -1)) # Center the distrib. at <-1, -1>
y_2 = np.random.standard_normal((150, 2))
y_2 += np.array((1, 1)) # Center the distrib. at <1, 1>
plt.scatter(y_1[:,0], y_1[:,1], color = 'c')
plt.scatter(y_2[:,0], y_2[:,1], color = 'b')
plt.show()
2.2.3.2 Give each point a different color
Points of different categories need to be drawn with different colors to observe the differences between different categories. Taking Fisher's iris data set as an example, the data in the data set is similar to the following:
5.0,3.3,1.4,0.2,Iris-setosa
7.0,3.2,4.7,1.4,Iris-versicolor
4.0,5.2,9.5,9.3,Iris-virginica
Each point of the dataset is stored in a comma-separated list. The last column gives the label of each point (the label contains three categories: Iris-virginica
, Iris-versicolor
and Iris-Vertosa
). In the example, the colors of the points will depend on their labels, like this:
label_set = (
b'Iris-setosa',
b'Iris-versicolor',
b'Iris-virginica',
)
def read_label(label):
return label_set.index(label)
data = np.loadtxt('data.data', delimiter = ',', converters = { 4 : read_label })
color_set = ('c', 'y', 'm')
color_list = [color_set[int(label)] for label in data[:,4]]
plt.scatter(data[:,0], data[:,1], color = color_list)
plt.show()
For each of the three possible labels, we specify a unique color, with the color color_set
defined in and the label label_set
defined in . The th label label_set
in is associated with the th color in . We then use them to convert the list of labels into a list of colors . Then just call once to display all points and their colors.i
color_set
i
color_list
plt.scatter()
2.2.4 Use custom colors for the edges of the scatter plot
Just like color
the parameter controls the color of a point, you can use edgecolor
the parameter to control the color of the edge of a data point. You can set the same color for the edge of each point:
data = np.random.standard_normal((100, 2))
plt.scatter(data[:,0], data[:,1], color = '1.0', edgecolor='r')
plt.show()
In addition to setting the same color for each point's edges, you can also set a different color for each point's edges as described in the Defining a Different Color for Each Point section.
2.2.5 Draw bar chart using custom colors
Controlling the colors used to draw bar charts works in the same way as line and scatter plots, i.e. via optional parameters color
:
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, color='m')
plt.barh(x, -m_pop, color='c')
plt.show()
Likewise, drawing a bar chart with custom colors using plt.bar()
the and functions works exactly the same as with , you just need to set the optional parameters , and you can also use the parameter to control the color of the bar edges. `plt.barh()
plt.scatter()
color
edgecolor
Example:
values = np.random.randint(100, size = 50)
color_set = ('c', 'm', 'y', 'b')
color_list = [color_set[(len(color_set) * val) // 100] for val in values]
plt.bar(np.arange(len(values)), values, color = color_list)
plt.show()
2.2.6 Draw a pie chart using custom colors
The method of customizing pie chart colors is similar to that of bar charts:
color_set = ('c', 'm', 'y', 'b')
values = np.random.rand(6)
plt.pie(values, colors = color_set)
plt.show()
The pie chart accepts a list of colors using colors
the argument (note, here colors
, not as plt.plot()
used in color
). However, if the number of colors is less than the number of elements in the input value list, then plt.pie()
the colors in the color list are cycled through. In the example, using a list of four colors, two of the colors will be used twice in order to color a pie chart containing six values.
2.2.7 Draw box plots using custom colors
values = np.random.randn(100)
b = plt.boxplot(values)
for name, line_list in b.items():
for line in line_list:
line.set_color('m')
plt.show()
2.2.8 Drawing a scatter plot using color mapping
If you want to use multiple colors in your graphics, defining each color one by one is not the best solution. Color mapping can solve this problem. Color mapping defines colors as a continuous function in which a variable corresponds to a value (color). Matplotlib
Several common colormaps are provided; most are continuous color gradients. Colormaps matplotib.cm
are defined in the module, which provides functions for creating and using colormaps. It also provides a selection of predefined colormaps. The function plt.scatter()
accepts a list of values for the argument. When argument values color
are provided , these values will be interpreted as indices into the color map:cmap
n = 256
angle = np.linspace(0, 8 * 2 * np.pi, n)
radius = np.linspace(.5, 1., n)
x = radius * np.cos(angle)
y = radius * np.sin(angle)
plt.scatter(x, y, c = angle, cmap = cm.hsv)
plt.show()
2.2.9 Drawing bar charts using color mapping
plt.scatter()
The function has built-in support for color mapping, and some other drawing functions also have built-in support for color mapping. However, some functions (such as plt.bar()
) do not have built-in support for colormaps, in which case Matplotlib
the colors can be generated explicitly from the colormap:
Use matplotlb’s color module:
values = np.random.randint(99, size = 50)
cmap = cm.ScalarMappable(col.Normalize(0, 99), cm.binary)
plt.bar(np.arange(len(values)), values, color = cmap.to_rgba(values))
plt.show()
Start by creating a colormap cmap
that [0, 99]
maps values in the range to matplotlib.cm.binary
the color of . The function then cmap.to_rgba
converts the list of values into a list of colors. Therefore, although plt.bar()
there is no built-in color mapping support, color mapping can still be implemented using uncomplicated code.
2.2.10 Create a custom color scheme
Matplotlib
The default colors used are primarily intended for printing documents or publications. Therefore, by default, the background is white, while labels, axes, and other annotations are displayed in black. In some different usage environments, we may need to use the color scheme; for example, setting the figure background to black, annotation settings is white. In Matplotlib
, various objects such as axes, graphs, and labels can be modified individually, but changing the color configuration of each of these objects individually is not optimal. We can use the method introduced in "Matplotlib Installation and Configuration" to centrally change all objects by modifying the configuration to configure their default color or style:
mpl.rc('lines', linewidth = 2.)
mpl.rc('axes', facecolor = 'k', edgecolor = 'w')
mpl.rc('xtick', color = 'w')
mpl.rc('ytick', color = 'w')
mpl.rc('text', color = 'w')
mpl.rc('figure', facecolor = 'k', edgecolor ='w')
mpl.rc('axes', prop_cycle = mpl.cycler(color=[(0.1, .5, .75),(0.5, .5, .75)]))
x = np.linspace(0, 7, 1024)
plt.plot(x, np.sin(x))
plt.plot(x, np.cos(x))
plt.show()
2.3 Custom styles
2.3.1 Customize line style and line width
In practice, in addition to color, in most cases we also need to control the line style of graphics to add variety to the line style.
2.3.1.2 Customized line style
linestyle
argument is an optional parameter in Matplotlib used to specify the line style. It is used to control the appearance style of lines when drawing linear graphs such as line graphs and curve graphs.
linestyle
Common values for parameters are as follows:
-
'-'
or'solid'
: solid line (default) -
'--'
or'dashed'
: dashed line -
':'
or'dotted'
: dotted line -
'-.'
or'dashdot'
: dotted line
Example:
def gaussian(x, mu, sigma):
a = 1. / (sigma * np.sqrt(2. * np.pi))
b = -1. / (2. * sigma ** 2)
return a * np.exp(b * (x - mu) ** 2)
x = np.linspace(-6, 6, 1024)
plt.plot(x, gaussian(x, 0., 1.), color = 'y', linestyle = 'solid')
plt.plot(x, gaussian(x, 0., .5), color = 'c', linestyle = 'dashed')
plt.plot(x, gaussian(x, 0., .25), color = 'm', linestyle = 'dashdot')
plt.show()
Use the parameter plt.plot()
of linestyle
to control the style of the curve. Other available line styles include: solid
, dashed
, dotted
, dashdot
. Similarly, line style settings are not limited to plt.plot()
this parameter. Any graphics composed of lines can use this parameter. It can also be said that linestyle
the parameter can be used for all commands involving line rendering. For example, you can modify the line style of a bar chart:
n = 10
a = np.random.random(n)
b = np.random.random(n)
x = np.arange(n)
plt.bar(x, a, color='c')
plt.bar(x, a+b, bottom=a, color='w', edgecolor='black', linestyle = 'dashed')
plt.show()
edgecolor
The default color of the edge can be changed through the parameter
2.3.1.2 Customized line width
Use linewidth
the parameter to modify the thickness of the line. By default, linewidth
this is set to 1 unit. Use line thickness to visually emphasize a specific curve.
Example:
def gaussian(x, mu, sigma):
a = 1. / (sigma * np.sqrt(2. * np.pi))
b = -1. / (2. * sigma ** 2)
return a * np.exp(b * (x - mu) ** 2)
x = np.linspace(-6, 6, 1024)
for i in range(64):
samples = np.random.standard_normal(50)
mu, sigma = np.mean(samples), np.std(samples) #平均值和标准差
plt.plot(x, gaussian(x, mu, sigma), color = '.75', linewidth = .5)
plt.plot(x, gaussian(x, 0., 1.), color = 'c', linewidth = 3.)
plt.show()
2.3.2 Control fill style
Matplotlib
Provides hatch patterns for filling flat surfaces. These fill patterns play an important role in graphics that only contain black and white.
Example:
n = 10
a = np.random.random(n)
b = np.random.random(n)
x = np.arange(n)
plt.bar(x, a, color='w', hatch='x', edgecolor='black')
plt.bar(x, a+b, bottom=a, color='w', edgecolor='black', hatch='/')
plt.show()
Functions with fill renderability (such as plt.bar()
) can use the optional parameter hatch
to control the fill style. The optional values of this parameter include: /
, , \
, |
, -
, +
, x
, o
, and , each value corresponds to a different fill pattern; the parameter can be used Controls the color of the fill pattern.O
.
*
edgecolor
2.3.3 Control tags
2.3.3.1 Control mark style
In "Matplotlib Graph Drawing" , we have learned how to draw curves and understood that curves are composed of connections between points; in addition, scatter plots represent each point in the data set. And Matplotlib
provides a variety of shapes that can replace the point style with other types of markers. Markers can be specified in the following ways:
-
Predefined token: A predefined shape, represented as
[0, 8]
an integer in a range or some predefined string. -
vertex list: A list of value pairs used as coordinates for the shape's path.
-
Regular polygon: A triple representing
N
a regular polygon with sides(N, 0, angle)
, whereangle
is the rotation angle. -
Star polygon: It is represented as a triplet
(N, 1, angle)
, representingN
a regular star with sides, whereangle
is the rotation angle.
a = np.random.standard_normal((100, 2))
a += np.array((-1, -1))
b = np.random.standard_normal((100, 2))
b += np.array((1, 1))
plt.scatter(a[:,0], a[:,1], color = 'm', marker = 'x')
plt.scatter(b[:,0], b[:,1], color = 'c', marker = '^')
plt.show()
Using marker
the parameter, you can specify different markers for each data collection.
What if we need to define different styles for each point? Unlike color
parameters, marker
parameters do not accept a list of markup styles as input. Therefore, we cannot implement plt.scatter()
a single call of to display multiple point sets with different labels. The solution is to separate each type of data points into different collections and call separate plt.scatter()
calls for each collection:
label_list = (
b'Iris-setosa',
b'Iris-versicolor',
b'Iris-virginica',
)
colors = ['c','y','m']
def read_label(label):
return label_list.index(label)
data = np.loadtxt('data.data', delimiter = ',', converters = { 4 : read_label })
marker_set = ('^', 'x', '.')
for i, marker in enumerate(marker_set):
data_subset = np.asarray([x for x in data if x[4] == i])
plt.scatter(data_subset[:,0], data_subset[:,1], color = colors[i], marker = marker)
plt.show()
For plt.plot()
, markup styles can also be accessed using the same markup parameters. When the data points are dense, displaying each point with a marker will cause the picture to be cluttered, so the parameter Matplotlib
is provided markevery
to allow N
a marker to be displayed for every every point:
Example:
x = np.linspace(-6, 6, 1024)
y_1 = np.sinc(x)
y_2 = np.sinc(x) + 1
plt.plot(x, y_1, marker = 'x', color = '.75',label = 'y-1')
plt.plot(x, y_2, marker = 'o', color = 'k', markevery = 64,label = 'y-2')
plt.legend()
plt.show()
2.3.3.2 Controlling the size of markers
The size of the marker s
is controlled by the optional argument:
Example:
a = np.random.standard_normal((100, 2))
a += np.array((-1, -1))
b = np.random.standard_normal((100, 2))
b += np.array((1, 1))
plt.scatter(a[:,0], a[:,1], c = 'm', s = 100.)
plt.scatter(b[:,0], b[:,1], c = 'c', s = 25.)
plt.show()
The size of the marker is set by plt.scatter()
the parameter s
, but note that it sets the marker's surface area ratio rather than its radius. plt.scatter()
The function can also accept a list as s
input parameter, which represents the corresponding size of each point.
Example:
m = np.random.standard_normal((1000, 2))
r_list = np.sum(m ** 2, axis = 1)
plt.scatter(m[:, 0], m[:, 1], c = 'w', edgecolor='c', marker = 'o', s = 32. * r_list)
plt.show()
For the Plot method, plt.plot()
the function allows changing the size of the markers with the help of markersize
(or abbreviated as ms
) parameter, but this parameter does not accept a list as input.
2.3.3.3 Custom tags
Although Matplotlib
a variety of marker shapes are available. But in some cases we may still not find the right shape for our specific needs. For example, we might want to use a company logo, etc. as a shape. In Matplotlib
, describe a shape as a path—a series of connected points. Therefore, if we want to define our own marker shape, we must provide a series of points:
Example:
shape_description = [
( 1., 2., mpath.Path.MOVETO),
( 1., 1., mpath.Path.LINETO),
( 2., 1., mpath.Path.LINETO),
( 2., -1., mpath.Path.LINETO),
( 1., -1., mpath.Path.LINETO),
( 1., -2., mpath.Path.LINETO),
(-1., -2., mpath.Path.LINETO),
(-1., -1., mpath.Path.LINETO),
(-2., -1., mpath.Path.LINETO),
(-2., 1., mpath.Path.LINETO),
(-1., 1., mpath.Path.LINETO),
(-1., 2., mpath.Path.LINETO),
( 0., 0., mpath.Path.CLOSEPOLY),
]
#mpath.Path.MOVETO表示将移动到指定点,mpath.Path.LINETO表示在指定点之间绘制一条直线,mpath.Path.CLOSEPOLY表示绘制一个闭合路径。
u, v, codes = zip(*shape_description)
#这行代码使用zip()函数和解包操作将shape_description列表中的元组拆分成三个分别包含x坐标、y坐标和代码的元组。
my_marker = mpath.Path(np.asarray((u, v)).T, codes)
#这是使用mpath.Path()方法创建自定义的路径对象my_marker。这个路径由x坐标数组u和y坐标数组v组成,并使用对应的代码数组codes来指定路径上的点和连接方式。
data = np.random.rand(8, 8)
plt.scatter(data[:,0], data[:, 1], c = 'm', marker = my_marker, s = 75)
plt.show()
Path
The object's constructor takes as input a list of coordinates and a list of instructions; one instruction per coordinate, uses a list to fuse the coordinates and instructions together, and then passes the coordinate list and instructions to the path constructor.
Shapes are described by movement of the cursor:
-
MOVETO
: This command moves the cursor to the specified coordinates without drawing a line. -
LINETO
: This will draw a straight line between the current point of the cursor and the target point, and move the cursor to the target point. -
CLOSEPOLY
: This directive is only used to close the path, every shape ends with this directive.
In theory, any shape is possible.