Summary of three matplotlib drawing basic functions

Introduction to matplotlib

matplotlib is a python plotting library designed with the idea of ​​being able to generate powerful visualizations in an easy and simple way, with just a few lines of code to generate plots, histograms, power spectra, bar charts, error plots, scatter plots, etc. , is one of the core libraries for data analysis.
The most widely used matplotlib is the matplotlib.pyplot module.

The figure below is the basic flow of matplotlib drawing. Our explanation of the functions of the matplotlib.pyplot module is based on this flow:
insert image description here

Process one

create canvas

function effect
plt.figure(num=None, figsize=None, dpi=None) (1) num: the identity of the num: window can be identified. If this parameter is not provided, the parameter will be incremented when the window is created, and if provided, the window will exist with the num as the Id. (2) figsize: optional parameter, an array of width and height in inches. Default is [6.4, 4.8] (3) dpi: optional parameter, integer. Indicates the resolution of the window, the default value is 100.

create subgraph

function effect
fig,axes = subplots(nrows=1, ncols=1, sharex=False, sharey=False) (1) Create a canvas (2) nrows, ncols respectively represent the number of rows and columns of the created subgraph, the default value is 1 (3) sharex, sharey parameters: bool or {'none', 'all', 'row ', 'col'} (4) The return value fig is the identity of the canvas, and axes represent the subgraph
axes = fig.add_subplot( *args, **kwargs) This function cannot create a canvas, and you should create a canvas before using it (fig represents the canvas variable), for example: axes = fig.add_subplot(3,3,2) means that the canvas is divided into subplots with 3 rows and 3 columns, and the second subplot is selected graph and returns the identity of that subgraph

The parameters of sharey and sharex are the same, take sharex as an example:

sharex meaning
True or all Represents that all subplots share the x-axis
row Represents that each row of subplots shares an x-axis
False or none The x-axis of each subplot is independent
col Each column of subplots shares an x-axis

Once the process is completed, the case shows:

import matplotlib.pyplot as plt


#创建画布
fig = plt.figure(figsize = [5,4],dpi = 100)
print('fig画布的身份标识{}'.format(fig))

#使用add_subplot创建子图
axes = fig.add_subplot(3,3,5)
axes.set_title('number ten')

#使用subplots创建画布和子图
fig2,axes = plt.subplots(nrows = 2,ncols = 2)
axes[0,1].set_title('number two')
print('fig2画布的身份标识{}'.format(fig2))

plt.show()

renderingsinsert image description here

Process two

We have prepared the big frame, and the next step is to draw diagrams and add details to the canvas or sub-picture.
The first is the title of the chart, the scale of the horizontal and vertical axes, range, name, etc.

function effect
plt.title(label, fontdict=None, loc=None, pad=None, *, y=None, **kwargs) (1)label is the title text to be set (2)fontdict is an optional parameter used to set the font properties of the title, such as font name, size, color, etc. (3) The loc parameter is used to specify the position of the title, which can be represented by a string ('left', 'center', 'right', etc.) or a number. (4) The pad parameter is used to specify the distance between the title and the border of the graph.
plt.xlabel(xlabel, fontdict=None, labelpad=None, *, loc=None, **kwargs)和plt.ylabel (1) xlabel: the name of the x-axis (2) fontdict optional parameter, which is used to set the font attribute of the x-axis name (3) the distance between the x-axis name and the graph boundary (4) loc parameter is used to specify the position of the title
plt . xlim ( * args , ** kvargs ) and plt . ylim Display or set the range of the x-axis, if no parameter is filled, the function returns the left and right range of the x-axis. Filling in the parameters means setting the representation range of the x-axis. Example plt.xlim(-1,2), plt.xlim(left=-1), plt.xlim(right=2)
plt.xticks(ticks=None, labels=None, *, minor=False, **kwargs)和plt.yticks (1) ticks: a list of x-axis scale positions (2) labels: the label text placed at the specified scale position. When the ticks parameter has an input value, this parameter can be passed into the parameter (3) minor: The default value is to display the scale according to the given list of ticks. When it is True, the ticks will have no effect, and the scale is selected by the system
plt.legend(title,loc,frameon) (1) title: the title of the legend (2) loc: the position of the legend in the chart (3) frameon: set whether to include a frame. are optional parameters

The ontdict in the above table is to set multiple attribute values ​​at one time, and then pass in multiple functions to control the font attributes
of multiple functions . For example:

fontdict = {
    
    'fontsize': 10, 'family': ['serif','SimSun'],'weight':'bold'}
ax.set_ylabel(label, fontdict=fontdict)

Then we draw line, scatter, column and other charts

color illustrate color illustrate
‘b’ blue ‘m’ magenta
‘g’ green ‘y’ yellow
‘r’ red ‘k’ black
‘c’ green ‘w’ White
‘#008000’ RGB certain color
linestyle illustrate
‘-‘ solid line
‘–’ Dashed line
‘-.’ Dotted line
‘:’ dotted line
’ ’ ’ ‘ wireless
marker illustrate marker illustrate
‘.’ point marker ‘1’ lower triangle mark
‘,’ Pixel markers (tiny dots) ‘2’ upper triangle mark
‘o’ solid circle mark ‘3’ Left flower triangle mark
‘v’ inverted triangle mark ‘4’ Right flower triangle mark
‘^’ upper triangle mark ’s’ solid square marker
‘>’ right triangle mark ‘p’ solid pentagram
‘<’ left triangle mark ‘*’ star mark
‘h’ vertical hexagon mark ‘d’ skinny diamond marker
‘H’ horizontal hexagon mark ‘|’ vertical line marker
‘+’ cross mark ‘D’ diamond mark
‘x’ x mark
function effect
plt.plot((x, y, color, linestyle, marker, markerfacecolor, markersize) Commonly used parameters for line charts: (1) x, y are input lists, and line charts are drawn according to x, y (2) color: control color (3) linestyle: line style (4) marker: mark style (5) markerfacecolor : Marker color (6) markersize: Marker size
plt.bar(x, height, width=0.8, bottom=None, *, align=‘center’, data=None, **kwargs) 柱状图(1)x:柱子在x轴上的坐标。注意x可以为字符串数组! (2)height:柱子的高度,即y轴上的坐标 (3)width:柱子的宽度。浮点数或类数组结构。默认值为0.8。(4)bottom:柱子的基准高度。浮点数或类数组结构。默认值为0。(4)align:柱子在x轴上的对齐方式.取值{‘center’, ‘edge’},默认为’center’。‘center’:x位于柱子的中心位置。‘edge’:x位于柱子的左侧。如果想让x位于柱子右侧,需要同时设置负width 以及align=‘edge’。color:柱子的填充色.hatch:柱子填充符号
plt.pie(x, labels=,autopct=,colors) 饼状图:(1)x:数量,自动算百分比 (2)labels:每部分名称 (3)autopct:占比显示指定%1.2f%% (4)colors:每部分颜色
plt.scatter(x, y, s=20, c=‘b’, marker=‘o’, alpha=None, ) 散点图:x,y:将要绘制的数据,s:表示一个点的大小,可以为一个数或者数组,c:颜色,可为数组,marker:标记样式,alpha:点的透明度

流程三

图像的保存与显示

函数 作用
plt.show() 显示绘制的图表
plt.savefig(fname, dpi=None ) fname:指定格式图片或者指定文件位置 dpi:画质

如果plt.show() 在plt.savefig()前,就会导致保存图片是空白的情况。

其它函数与注意事项

注意事项

(1)在画布上使用子图进行标题,x,y轴的刻度,范围,名称等设置时可能会出现以下报错TypeError: 'Text' object is not callable
检查你的代码如下

axes.title('number ten')

改为

axes.set_title('number ten')

That's it. Because title and set_title are two interfaces of matplotlib, only the interface of set_title can be used for subplots, and other functions are similar to add set_
(2) I forgot to introduce gridding above, here I add
plt.grid(visible= None, which='major', axis='both', **kwargs)

function effect
visible Optional parameter, Boolean value; whether to display the grid line, if the keyword parameter of the grid line is set, it indicates that the grid line is to be set and visible; the default visible=None means the grid line is not visible
which Optional parameter, the grid line type to be operated: 'major', 'minor', 'both', default value: major, draw major scale grid lines
axis Optional parameter, which axis grid lines to operate: 'x', 'y', 'both', default: both , draw x-axis and y-axis grid lines at the same time
alpha Gridline Transparency
color grid line color
linestyle grid line type
linewidth grid line thickness

(3) Chinese does not display the problem, just add

plt.rcParams["font.sans-serif"]=["SimHei"] #设置字体
plt.rcParams["axes.unicode_minus"]=False #该语句解决图像中的“-”负号的乱码问题

3D chart

First, let's create the 3D object

#方法一,利用关键字
from matplotlib import pyplot as plt
from mpl_toolkits.mplot3d import Axes3D

#定义坐标轴
fig = plt.figure()
ax1 = plt.axes(projection='3d') #直接在画布上创建
ax = fig.add_subplot(111,projection='3d')  #多个子图的3D图表


#方法二,利用三维轴方法
from matplotlib import pyplot as plt
from mpl_toolkits.mplot3d import Axes3D

#定义图像和三维格式坐标轴
fig=plt.figure()
ax2 = Axes3D(fig)

The second method of creating 3D objects here is not as easy to use as the first method. The following example is based on the first method.

from matplotlib import pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
import numpy as np
x = np.array([i for i in range(10)])
y = np. array([i for i in range(10)])
z = 3*x+y

#定义坐标轴
fig = plt.figure()
#3D折线图
ax = fig.add_subplot(2,2,1,projection = '3d' ) #多个子图的3D图表
ax.set_title('one')
ax.plot3D(x,y,z)
#3D散点图
ax = fig.add_subplot(2,2,2,projection = '3d' ) #多个子图的3D图表
ax.set_title('two')
ax.scatter3D(x,y,z)
#3D散点图的第二种写法
ax =fig.add_subplot(2,2,3,projection = '3d' ) #多个子图的3D图表
ax.set_title('four')
ax.scatter(x,y,z)
plt.show()

insert image description here

end

It's really not easy to organize these things, I hope it can help you, and I hope you can support me a lotinsert image description here

Guess you like

Origin blog.csdn.net/m0_59151709/article/details/130290908