Python visualization--detailed explanation of matplotlib.pyplot drawing

  • Create canvas

We use the plt.figure() function to create a blank canvas. Among the commonly used parameters, figsize requires a tuple value, which represents the horizontal and vertical coordinate ratio of the blank canvas; dpi represents the number of pixels, which is actually the control of the image size.

Usually used together with plt.subplot(). As mentioned below, subplot is to create a subplot.

# 创建画布
plt.figure(figsize=(8, 6), dpi=80) 
  • Create subgraph

subplot(nrows,ncols,sharex,sharey,subplot_kw,**fig_kw)

nrows represents the number of rows in subplot

ncols represents the number of columns of subplot

sharex represents the scale of the x-axis in the subplot. All subplot x-axes should maintain the same scale.

sharey represents the scale of the y-axis in the subplot. All subplot y-axes should maintain the same scale.

  • Create multiple subgraphs

The subplots parameters are similar to subplot

import numpy as np  
import matplotlib.pyplot as plt

x = np.arange(0, 100)  
#划分子图
fig,axes=plt.subplots(2,2)
ax1=axes[0,0]
ax2=axes[0,1]
ax3=axes[1,0]
ax4=axes[1,1]
#作图1
ax1.plot(x, x)  
#作图2
ax2.plot(x, -x)
 #作图3
ax3.plot(x, x ** 2)
ax3.grid(color='r', linestyle='--', linewidth=1,alpha=0.3)
#作图4
ax4.plot(x, np.log(x))  
plt.show() 
  • Draw content

The linestyle parameter represents the drawn line style. Available line styles include '-', '--', '-.', ':', 'None', ' ', '', 'solid', 'dashed', ' dashdot', 'dotted', 11 categories in total. The label parameter is a name tag for the line segment, which is used for subsequent drawing of the legend.

# 绘制曲线
plt.plot(x, y1, color='r', linestyle='--', label='Shanghai')
plt.plot(x, y2, color='g', linestyle='-.', label='Beijing')
  • Draw legend

The plt.legend() function is used to draw the legend. The loc parameter indicates the position of the legend. The default is best, which means automatic selection.

plt.legend(loc='best')  # 提供11种不同的图例显示位置
  • Set axis scale

# 设置刻度和步长
z = range(-10, 45)
x_label = ["10:{}".format(i) for i in x]
plt.xticks(x[::5], x_label[::5])
plt.yticks(z[::5])
  • Add grid information

The plt.grid() function is used to add the background grid in the picture. Among the commonly used parameters, alpha represents the transparency setting, and linewith represents the line width.

plt.grid(linestyle='--', alpha=0.5, linewidth=2)
  • Add title

The plt.xlabel(), plt.ylabel() and plt.title() functions are used to set the x-axis, y-axis and title information of the icon respectively.

# 添加标题
plt.xlabel('Time/ min')
plt.ylabel('Temperature/ ℃')
plt.title('Curve of Temperature Change with Time')
  • Save and display

# 保存和展示
# plt.savefig('./plt_img/test2.png')
plt.show()

Draw a line chart

plot(x, y, format_str, **kwargs) : Draw a line chart.

  • x and y are data sequences, format_str specifies the polyline style, such as color, line type, etc.

  • **kwargs can pass other parameters, such as label (add a label to the polyline) and linewidth (set the width of the polyline), etc.

import matplotlib.pyplot as plt
import numpy as np

x = np.arange(0, 10, 0.1)
y = np.sin(x)

plt.plot(x, y, 'r-', label='sine curve', linewidth=2)
plt.xlabel('x')
plt.ylabel('y')
plt.title('sine curve')
plt.legend()
plt.show()

Draw a scatter plot

scatter(x, y, s=None, c=None, marker=None, **kwargs) : Draw a scatter plot.

  • x and y are data sequences, s specifies the size of the point, c specifies the color of the point, and marker specifies the shape of the point.

  • **kwargs can pass other parameters, such as label (add labels to scatter points) and alpha (set scatter point transparency), etc.

import matplotlib.pyplot as plt
import numpy as np

x = np.random.rand(50)
y = np.random.rand(50)
colors = np.random.rand(50)
sizes = 500 * np.random.rand(50)

plt.scatter(x, y, s=sizes, c=colors, marker='o', alpha=0.5, label='random data')
plt.xlabel('x')
plt.ylabel('y')
plt.title('scatter plot')
plt.legend()
plt.show()

Draw a bar chart

bar(x, height, width=0.8, bottom=None, align='center', **kwargs) : Draw a bar chart.

  • x is the x-axis coordinate of the column, height is the height of the column, width specifies the width of the column, bottom specifies the bottom position of the column, and align specifies the alignment of the column.

  • **kwargs can pass other parameters, such as label (add a label to the column) and color (set the column color), etc.

import matplotlib.pyplot as plt
import numpy as np

x = np.array(['A', 'B', 'C', 'D', 'E'])
y = np.array([10, 24, 36, 42, 15])

plt.bar(x, y, align='center', color='b', label='data')
plt.xlabel('category')
plt.ylabel('value')
plt.title('bar chart')
plt.legend()
plt.show()

Guess you like

Origin blog.csdn.net/Edenms/article/details/129289334