Using Matplotlib to draw common charts in Python

Matplotlib is a very powerful Python drawing tool. By drawing line graphs, scatter plots, contour plots, bar charts, histograms, 3D graphics, and even graphic animations, you can more intuitively present scientific calculations. A lot of data.

1. Basic elements

In the hierarchical structure of matplotlib, the highest level is the "state-machine environment" provided by the matplotlib.pyplot module, through which image elements such as curves, text, pictures, etc. are drawn for the current dimension. The next layer is the first-level object-oriented interface. In this layer, users can use pyplot to create and track image objects, and thus create one or more data axis systems, which are later used for drawing. .

The elements of the image are as follows:

Figure refers to the entire picture object, used to contain one or more data axis system (Axes), if there is no Axes, the image is empty.

fig = plt.figure()  # 创建一个图像对象
fig.suptitle('No axes on this figure')  # 添加一个标题

fig, ax_lst = plt.subplots(2, 2)  # 创建包含2×2个子图的图像

Aexs is a complex number of Axis, translated as axis system and coordinate system, which can be understood as a sub-graph of the entire image (Figure), a graph can contain multiple sub-graphs, we draw specific charts in the sub-graph . The sub-picture object can be created by plt.plot () function, the title of the sub-picture can be set by set_title (), and the labels of the horizontal and vertical coordinates of the figure are set by set_xlabel () and set_ylabel ().

Axis refers to the specific coordinate axis, where trick represents the scale of the coordinate axis, the location of the scale is controlled by the Location object, and Formatter formats the character string displayed by the scale, and the display of the scale can be precisely controlled by these two objects.

Artist object: Any element in the image can be regarded as an Artist, including 2D lines (Line), text, and Axis and image Figure, when the picture is rendered, these objects are drawn into the picture. Most Artist objects are bound to a specific axis, Axis, and such objects cannot be shared between axis systems.

The input data of matplot is best converted to np.array type. Using other data types such as np.matrix, pandas, etc. may report errors, so convert the other types through numpy before passing in the parameters.

The necessary libraries and encoding methods suggested by matplotlib are as follows. When drawing, first create the Figure object and the sub-picture object ax through the plt interface, and then call the function drawing through ax. By defining the function to draw the image, you can avoid many repetitive operations and facilitate code maintenance . For example, the following defines my_plotter () to complete image drawing, passing in sub-graph ax, two data data1, data2, and image drawing parameters param_dic.

import matplotlib.pyplot as plt    # 引入必要的库
import numpy as np
%matplotlib inline     

# 定义函数进行图像绘制操作
def my_plotter(ax,data1,data2,param_dic):
    ax.plot(x, y,**param_dic)

x = np.arange(0, 10, 0.2)    # 准备数据
y = np.sin(x)

fig, ax = plt.subplots(1)    # 创建子图
my_plotter(ax,x, y,{ 'linestyle':'dashed','label':'sinx'})  # 调用函数绘制图像

2. Basic usage

Create image and draw function

First, you need to import the necessary function libraries matplotlib.pyplot and numpy. If you use jupyternotebook, you need to add% matplotlib inline setting to display the picture

Create an image by plt.figure (), where the num attribute indicates the window where the image is displayed, and the figsize attribute can specify the size of the image

Use plt.plot () to draw the curve. The first two array parameters are the coordinate values ​​of the image x and y. After the optional parameters, you can set the color (line), line width, style (linestyle), and opacity (alpha) of the line

plt.scatter () draws a single point instead of a connected curve. Similarly, the first two parameters are arrays, corresponding to the x and y coordinates of the point. Attribute s sets the size of the point, color sets the color

Finally, output the image through plt.show ()

import numpy as np
import matplotlib.pyplot as plt
# 设置行内显示
%matplotlib inline      

x = np.linspace(-5, 5, 50)        # 在-5~5内均匀取50个数
y1 = 2*x + 1                      # 定义一个线性函数
y2 = x**2                         # 定义一个二次函数

plt.figure(num=3, figsize=(10, 5))                              # 创建一个图形对象
plt.plot(x, y2, alpha=0.5)                                      # 绘制曲线
plt.plot(x, y1, color='red', linewidth=1.0, linestyle='--')     
plt.scatter([1],[1],s=200,color='orange')                       # 绘制一个点
plt.show()                                                      # 显示图像  

Adjust the axis

The range of the x coordinate axis can be adjusted through plt.xlim. Plt.xlabel sets the name of the coordinate axis. Similarly, plt.ylim and ylabel set the y axis. Chinese cannot be used in matlab, and the character set needs to be set.

plt.xticks () can customize the coordinate scale, pass the scale in the form of an array, and can pass in the scale value of the custom display

Set the position of the coordinate axis scale: get the x axis through the axes object.xaxis, and set the position through the set_ticks_position () method, the optional positions are: top, bottom, both, default, none, the corresponding y axis scale is: left , Right, both, default, none

# 设置行内显示
%matplotlib inline  
plt.rcParams['font.sans-serif'] = ['SimHei']    # 设置字符集显示中文
plt.rcParams['axes.unicode_minus'] = False      # 设置负号正确显示

x = np.linspace(-5, 5, 50)        
y1 = 2*x + 1    
y2 = x**2   

plt.figure(num=3, figsize=(10, 5))   
plt.plot(x, y2)     
plt.plot(x, y1, color='red', linewidth=1.0, linestyle='--')
plt.xlabel('x轴')                                           # 设置显示x轴标签
plt.xlim(-2,2)                                              # 设置x轴的范围为-2~2
plt.xticks([-2,-1,0,1,2])                                   # 设置x轴刻度
axes=plt.gca()
axes.xaxis.set_ticks_position('top')                        # 设置x坐标显示在上边框
plt.ylabel('y轴')
plt.ylim(-5,5)                                              # 设置y轴的范围为-5~5
plt.yticks([-3,-1,0,1,3],['低','较低','中等','高','较高'])     # 自定义刻度值
axes.yaxis.set_ticks_position('left')                       # 设置y坐标显示在左边框
        

We can also set the four borders of the picture, get the axis object axes through plt.gca (), get the right border through .spines ['right'], and then set_color to set its color, use set_position () to set Border position

axes.spines['right'].set_color('none')                      # 获取并设置右边框透明
axes.spines['top'].set_color('none')
axes.spines['bottom'].set_position(('data', 0))             # 将底部边框放到x=0的位置
axes.spines['left'].set_position(('data',0))                # 将左边框放到y=0的位置

3. Legend and annotation

When using plt.plot () for function drawing, you can add the label attribute to define the name of the curve.

Use plt.legend () to display the legend in the picture. Its loc property defines the position of the legend. The values ​​are 'best': 0, 'upper right': 1, 'upper left': 2, 'lower left': 3, ' lower right ': 4,' right ': 5,' center left ': 6,' center right ': 7,' lower center ': 8,' upper center ': 9,' center ': 10, where best stands for automatic Assign the best position

plt.plot(x, y1, label='linear')
plt.plot(x, y2, color='red', linewidth=1.0, linestyle='--', label='square')
plt.legend(loc='upper right')

You can also save the plot () result as l1, l2 objects, and then pass the handle attribute in the legend function, so that the legend function can add a legend to the line object specified in the figure, and set the content of the legend through the labels attribute.

l1, = plt.plot(x, y1)
l2, = plt.plot(x, y2, color='red', linewidth=1.0, linestyle='--')
# 对指定线条对象添加图例
plt.legend(handles=[l1,l2,], labels=['linear','square'], loc='best')

Add a comment to the picture through the plt.annotate () function, the first parameter is the content of the annotation, the fontsize annotation size, xycoords represents the position of the annotation point, data represents the data, xy represents the incoming data, textcoords = 'offset points' represents the position of the annotation according to the point offset, xytext sets the offset value, arrowprops is passed in the type and radian attribute of the arrow in dict

Add text to the picture through plt.text (), the first two parameters are the position of the text, the third parameter is the text content, fontdict sets the font and color of the text, ha = 'center' sets center alignment, va = ' bottom 'set to the bottom

plt.scatter([1],[1],s=100,color='orange')
# 添加自定义注释
plt.annotate('x²=2x-1',fontsize=20,xycoords='data',xy=(1,1),
             textcoords='offset points',xytext=(20,-30),
             arrowprops=dict(arrowstyle='->',connectionstyle='arc3,rad=.2'))
# 添加文本
plt.text(0.5,-1,"This is a text",fontdict={'size':15,'color':'green'},ha='center', va='top')

4. Draw the image

Scatter plot

Draw a scatter plot through scatter (), the s property is the size of the point, c is the color of the point, and the opacity of the alpha point

n = 1024    # data size
X = np.random.normal(0, 1, n) # 每一个点的X值
Y = np.random.normal(0, 1, n) # 每一个点的Y值
C = np.arctan2(Y,X)           # 为每个点生成颜色
plt.scatter(X, Y, s=75, c=C, alpha=0.5)

plt.show()

Bar graph

Use the plt.bar () function to draw a bar chart. The first two parameters are passed into the histogram's x position and y value array. The facecolor property sets the theme color, and edgecolor sets the border color.

n = 10
X = np.arange(n)        # X取1~12
Y1 = np.array([8,9,12,6,5,10,11,13,4,2])
Y2 = np.array([5,6,8,3,14,10,3,2,1,4])

plt.bar(X, Y1, facecolor='blueviolet', edgecolor='orange')
plt.bar(X, -Y2)

# 在柱状图顶部添加文本标注
for x, y in zip(X, Y1):
    plt.text(x, y , y, ha='center', va='bottom')
    
plt.show()

As shown in the right figure above, you can draw a histogram of the statistical distribution of data through plt.hist (data), and the parameter bins specifies the divided statistical interval.

Contour map

The data of the contour line is three-dimensional data, X and Y are independent variables, Z is the dependent variable function value, the same value is displayed as the contour line according to the difference of the function value

The color is filled by the plt.contourf () function. The first three parameters are the corresponding values ​​of X, Y, and Z. The color of the fill is cmp. Large map from blue to red

plt.contour () draws contour lines, colors = 'black' line color is black, linewidth = .5 line width is 0.5

Draw text through clabel (), inline fill text into line

Through the colorbar () function, you can add a function value corresponding to the color bar to the picture

n = 256
x = np.linspace(-3, 3, n)
y = np.linspace(-3, 3, n)
X,Y = np.meshgrid(x, y)     # 编制为256×256的网格,并把对应的坐标值返回给X、Y数组
def fun(x,y):               # 定义函数值Z,是一个三维函数椭圆抛物面
    return x**2+y**2

F = plt.contourf(X, Y, fun(X, Y), 8, alpha=.75,cmap='RdBu')             # 进行颜色填充
C = plt.contour(X, Y, fun(X, Y), 8, colors='black', linewidth=.5)       # 绘制等高线
plt.clabel(C, inline=True, fontsize=10)                                 # 标注文本
plt.colorbar(F)                                                         # 添加一个colorbar
plt.show()

Three-dimensional image

Before drawing 3D graphics, an additional package Axes3D needs to be introduced to convert the current image into a 3D image

Similarly, 3D graphs require three-dimensional data, X, Y compiled as a grid is an independent variable, Z is a function value

Draw 3D graphics through plt.plot_surface (), the attributes rstride and cstride represent the span of row and column respectively, the smaller the span, the denser the grid on the graph, and cmap is the color mapping scheme of the function value

The contour drawing function plt.contour () can be used to draw a projection on the plane for 3D graphics. Zdir = 'z' represents projection along the Z axis, so the projection will appear on the XY plane, and offset represents the offset position of the projection


import matplotlib.pyplot as plt
import numpy as np
from mpl_toolkits.mplot3d import Axes3D         #引入3D绘图库
%matplotlib inline

fig = plt.figure()
ax = Axes3D(fig)                                # 将当前图像转化为3D

X = np.arange(-10, 10, 0.5)
Y = np.arange(-10, 10, 0.5)
X, Y = np.meshgrid(X, Y)            # 编制 X-Y 平面的网格
Z = np.sqrt(X ** 2 + Y ** 2)        # Z值,定义为抛物面图形
ax.plot_surface(X, Y, Z, rstride=1, cstride=1, cmap='hsv')  # 绘制3D图
ax.contourf(X, Y, Z, zdir='z', offset=0, cmap='hsv')        # 添加沿Z轴方向的投影
plt.show()

Draw animation

Drawing animation requires additional animation library from matplotlib

Then draw one of the frames of the image first, for example, to draw the animation of sinx, take the argument x array at 0 ~ 2Π first, and then draw the curve line of its sinx

Then define the display function init () of the initial frame of the animation and return the initial line object. Then define the image display function animate of each frame, its parameter i represents the i th frame, and return different line objects according to i.

Finally, draw the image through animation.FuncAnimation (), the parameter fig is the picture object created before, init_func is the initialization display function, func is the display function of each frame, interval is the update frequency (unit ms), frames are the total number of animations Frame, blit to True means only update the changed points each time

Finally, the save () method of the returned ani object will be saved as a gif, and the writer used here is imagemagick

import numpy as np
from matplotlib import pyplot as plt
from matplotlib import animation                 # 引入动画库
%matplotlib inline

fig,ax=plt.subplots()                            # 创建画布

x=np.arange(0,2*np.pi,0.01)                      # 从0~2Π每隔0.01取一个数
line,=ax.plot(x,np.sin(x))                       # 绘制sinx的图像

def init():                                      # 定义初始帧显示函数
    line.set_ydata(np.sin(x))
    return line,
def animate(i):                                  # 定义每一帧的显示函数
    line.set_ydata(np.sin(x+i/10))
    return line,

# 绘制动画
ani=animation.FuncAnimation(fig=fig,init_func=init,func=animate,interval=20,frames=100,blit=True)
ani.save('sinx.gif',writer='imagemagick')        # 保存动画为gif

plt.show()

5. Multiple pictures

By plt.subplot () may be divided into a plurality of sub-graphs and select a location therein, e.g. subplot (2,2,1) representative creates 2 × 2 sub-picture, and wherein the selected first sub-graphs may be Omit the middle comma: subplot (224) means to select the fourth of the 2 × 2 subplots. In addition to drawing a subplot directly through the plt object, subplot can return a subplot object, and you can call plot () to plot through the subplot object.

import matplotlib.pyplot as plt
%matplotlib inline

plt.figure()

# 选中2×2子图中的第一个并画一条线
plt.subplot(2,2,1)
plt.plot([0,1],[2,3])
# 选中2×2子图的第四个画一条线
ax2=plt.subplot(224)
ax2.plt.plot([2,1],[3,4])

plt.show()

Note that the division here is not a real image division, but it is assumed that the entire image is divided in order to locate the sub-picture. For example, the following code first considers the canvas to select the first block in 2 rows and 1 column, which is the upper row, and then considers it to select the fourth block in 2 rows and 3 columns, and that is the first in the second row. Subdivisions of different sizes and positions can be obtained through different divisions and selections. If conflicting areas are involved, the subsequent subgraphs will overwrite the previous subgraphs.

# 划分为2行1列,选中第一块
plt.subplot(2,1,1)
plt.plot([0,1],[2,3])
# 划分为2行3列,选中第四块
plt.subplot(234)
plt.plot([2,1],[3,4])

   

The subplot2grid () method can be used to more conveniently divide and select sub-pictures, as shown below subplot2grid ((3, 3), (0, 0), colspan = 3) means to divide the picture into 3 × 3 areas, starting from line 0 Starting from column 0, the number of horizontally crossing colspan columns is 3, and the number of vertically crossing rowspan rows is 1 by default.

Note that the title and coordinate names can be set by title (), xlabel (), ylabel () in a whole picture, but in the sub-picture, you need to add a set_ before the function name

ax1 = plt.subplot2grid((3, 3), (0, 0), colspan=3)
ax1.plot([1, 2], [1, 2])    # 画小图
ax1.set_title('ax1_title')  # 设置小图的标题

ax2 = plt.subplot2grid((3,3), (2,1),colspan=2)
ax2.plot([2,1],[1,0])
ax2.set_xlabel('ax2_x')    # 设置小图的坐标轴名
ax2.set_ylabel('ax2_y')

The gridspec () function allows us to select submap regions as conveniently as using python arrays. Introduce this module from matplotlib before use, divide the image into regions by the Gridspec () function, and then return the gs object, which can be used to select sub-regions like an array. For example, gs [1,: 2], before the comma represents the selection of the row sequence number, if there is only one number represents the selection of all rows with a sequence number of 1, and the column after the comma, here 0: 2 represents the selection of all the columns from 0 to 2 before Column, where 0 can be omitted. Correspondingly, it can also be omitted if the end of the guide is selected, that is, gs [1,:]. If the serial number is -2, it means the penultimate is selected

import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec      # 引入库
%matplotlib inline

plt.figure()
gs = gridspec.GridSpec(3, 3)                # 将图像划分为3×3个区域
ax1 = plt.subplot(gs[0, :])                 # 选中第0行,所有列
ax2 = plt.subplot(gs[-1, -2])               # 选中倒数第1行,倒数第2列
plt.show()

 Through subplots (), multiple sub-graph objects can be created and returned at once. As shown below, the four sub-graphs are divided and returned to the four objects ax11 ~ ax22 in sequence, and the positions of the four objects must not be disordered. Among them sharex represents the image sharing X coordinate axis. plt.tight_layout () stands for compact display

f, ((ax11, ax12), (ax21, ax22)) = plt.subplots(2, 2, sharex=True, sharey=True)
ax11.scatter([1,2], [1,2])
plt.tight_layout()
plt.show()

Picture-in-picture: another picture can be added to the picture through the add_axes () of the figure object. The incoming parameter is the proportion of the four borders of the canvas on which the picture is located. Return the created sub-picture object ax, use ax to draw

x=[0,1]
y=[2,3]
fig = plt.figure()

ax1 = fig.add_axes([0.1, 0.1, 0.8, 0.8])    # 创建一个大图对象
ax1.plot(x, y, 'r')                         # 大图绘制
ax2 = fig.add_axes([0.2, 0.6, 0.25, 0.25])  # 创建小图
ax2.plot(x, y, 'b')                         # 小图绘制

plt.show()

Subgraph copy: The twinx () function of the subgraph object ax can copy another overlapping ax object with the same x axis at the same position, but the y axis is placed in a symmetric position, and the last two subgraphs will be displayed overlapping.

fig, ax1 = plt.subplots()
ax2 = ax1.twinx()                       # 拷贝ax对象

ax1.plot([0,1], [2,3], 'g-')            # 在原图中绘制
ax1.set_xlabel('X data')
ax1.set_ylabel('Y1 data', color='g')    # 原图的y轴在左侧
ax2.plot([0,1], [3,2], 'b-')            # 拷贝对象中绘图
ax2.set_ylabel('Y2 data', color='b')    # 拷贝子图的y轴在右侧
plt.show()

 

Published 124 original articles · Like 65 · Visit 130,000+

Guess you like

Origin blog.csdn.net/theVicTory/article/details/104571096