Backend Development
Python Tutorial
Detailed explanation of the basic parameters of matplotlib.pyplot in Python visualization summaryDetailed explanation of the basic parameters of matplotlib.pyplot in Python visualization summary
This article brings you relevant knowledge about Python, which mainly organizes issues related to the basic parameters of matplotlib.pyplot drawing, including figure, xlabel, grid, etc., as follows Let's take a look, I hope it will be helpful to everyone.

[Related recommendations: Python3 video tutorial ]
1. Introduction to matplotlib
The matplotlib library is a Python library Data visualization tool for drawing two-dimensional and three-dimensional charts
Features:
Use simple drawing statements to achieve complex drawing effects
Use interactive operations to achieve increasingly sophisticated graphic effects
Use embedded LaTex Output printing-level charts, scientific expressions and symbolic text
Achieve fine control over the components of the chart
Three drawing interfaces
pyplot: oriented to the current chart
axes: object-oriented
Pylab: following the matlab style
This article uses plot drawing (Displays the trend change of variables) to display the basic parameters of the drawing, using numpy The library obtains the drawing data (randomly), and the final graphics are not carefully thought out. Everything is mainly about displaying graphics parameters! ! !
Library used:
import matplotlib.pyplot as plt import numpy as np
2. Function usage of graphic elements
plot(): Display trend changes of variables
Usage: plt.plot(x, y, c, ls, lw, label, alpha, **kwargs)
x, Y: x, y axis value
C: Set color
LS: Line style of the folding diagram
# LW: The line width of the folding map
## Label: The label text of the markup content
## Alpha: Transparency
**kwargs: Specify the line2D attribute to be used
2.1. figure(): Background color
Usage: figure(num=None, figsize=None, dpi=None, facecolor=None,
edgecolor=None, frameon=True, FigureClass=Figure, clear=False, **kwargs)
num :
If this parameter is not provided, a new figure object will be created and the figure count will be increased. A numerical value that is stored in a numeric property of the figure object. If this parameter is present and a figure object corresponding to id exists, the figure object for id is activated. If the figur object corresponding to id does not exist, create it and return it. If the value of num is a string, the window title is set to this string
figsize: width and height in inches, the default value is rc figure.figsize (1 inch Equal to 2.54 cm)
dpi: figure resolution, the default value is rc figure.dpi
facecolor: Background color
plt.figure(figsize=(10, 10)) x = np.linspace(0.05, 10, 1000) # 在0.05到10的区间中,等差选取1000个,端点不属于 y = np.sin(x) plt.rcParams['font.sans-serif'] = ['SimHei'] plt.rcParams['axes.unicode_minus'] = False plt.plot(x, y, color='red', ls='-', label='sinx') plt.show()
2.2
xlim() and ylim():Set the numerical display range of x and y axes
How to use :plt.xlim(xmin,xmax)
xmin:x 轴上的最小值
xmax:x 轴上的最大值
2.3 xlabel()和 ylabel():设置 x,y 轴的标签文本
使用方法:plt.xlabel(fontsize, verticalalignment, horizontalalignment, rotation, bbox)
fontsize:数字或者(small,large,medium)
verticalalignment:距离坐标轴的位置(top,bottom,center,baseline)
hoizontalalignment:位置(center,right,left)
ratation:位置(vertical,horizontal,vertical)
bbox:添加边框
2.4 grid():绘制刻度线的网格线
使用方法:plt.grid(linestyle, color)
2.5 axhline():绘制平行于 x 轴额度水平参考线
使用方法:plt.axhline(y, c, ls, lw, label)
y:水平参考线的出发点
plt.figure(figsize=(10, 10))
x = np.linspace(0.05, 10, 1000) # 在0.05到10的区间中,等差选取1000个,端点不属于
y = np.sin(x)
plt.rcParams['font.sans-serif'] = ['SimHei']
plt.rcParams['axes.unicode_minus'] = False
plt.plot(x, y,
color='red',
ls='-',
label='sinx')
plt.xlim(1, 10)
plt.ylim(-1, 1)
plt.xlabel('x轴')
plt.ylabel('y轴')
plt.grid(ls=':',
color='blue') # 设置网格,颜色为蓝色
plt.axhline(0.5, color='green', lw=2, label="分割线") # 绘制平行于x轴的水平参考线,绿色,名称
plt.show()

(上图中绿色的线即为axjline()添加的参考线)
2.6 axvspan():绘制垂直于 x 轴的参考区域
使用方法:plt.axvspan( xmin, xmax ,facecolor, alpha)
xmin:参考区域的起始位置
xmax:参考区域的终止位置
facecolor:参考区域的填充颜色
alpha:参考区域填充颜色的透明度,[0~1]
注:其使用方法也可以用在 axhspan()上
在上一段代码添加
plt.axvspan(xmin=2, xmax=5, facecolor='r', alpha=0.2) # 绘制垂直于x轴的参考区域
即得到(注意:此段是区域)
2.7 xticks(),yticks()
获取或设置当前 x 轴或 y 轴刻度位置和标签(即设置 x 或 y 轴的标 签)
可以理解为设置xilim和ylim一样的效果,但可以指定范围和距离
plt.xticks(list(range(0, 12, 1))) # 调整刻度范围和刻度标签

注意看x轴,从原来的0~10到现在的0~11,可以通过设置第三个参数设置步长,这里设置为1
2.8 annotate():添加图形内容细节的指向型注释文本
函数方法:plt.annotate()
s:注释文本内容
xy:被注释的坐标点
xytext:注释文字的坐标位置
weight: Set the font line style (Ultralight, light, normal, regular, book, medium, roman, semibold, demibold, demi, bold, heavy, extrabold, black)
color: Set the font color; you can also set the RGB or RGBA type color; but it must be a floating point number between [0,1]
xycoords= The parameters are as follows
figure points: The points in the lower left corner of the figure
figure pixels: the pixels in the lower left corner of the figure
figure fraction: the lower left part of the figure
axes points: points at the lower left of the coordinate axis
axes pixels: the pixels at the lower left of the coordinate axis
data: Use the coordinate system of the annotated object
Arrow props: arrow parameters, parameter type is dictionary dict
width: the width of the arrow
headwidth: The width in points at the bottom of the arrow
headlength: the length of the arrow
shrink: part of the total length, "shrunk" from both ends
facecolor: arrow color (if the arrowstyle keyword is set, none of the above parameters can be used, but
To use these:
## because ##
##
##
####
####
#### 这里的黄色箭头和蓝色细长线即为参数方法添加的参数,实际使用过程中根据自己的实际所需使用,可以认为添加对图像的一些解释 (boxstyle:方框外形;circle:椭圆;darrow:双向箭头;larrow:箭头向左;rarrow:箭 头向右;round:圆角矩形;round4:椭长方形;roundtooth:波浪形边框 1;sawtooth: 波浪形边框 2;square:长方形) 函数方法:plt.text() x,y:表示坐标轴上的值
weight:
ultralightlight
normal
regular
book
medium
roman
semibold
demibold
demi
bold
heavy
extrabold
black
xycoodrds: figure points:图左下角的点
figure pixels:图左下角的像素
figure fraction:图的左下部分
axes points:坐标轴左下的点
data:使用被注释对象的坐标系统 arrowprops:箭头参数,参数类型为字典 dict
width:箭头的宽度
headwidth:箭头底部以点为单位的宽度
headlength:箭头的长度
shrink:总长度的一部分,从两端“收缩”
facecolor:箭头颜色 bbox:给标题增加外框
boxstyle:方框外形
circle:椭圆
darrow:双向箭头
larrow:箭头向左
rarrow:箭头向右
round:圆角矩形
round4:椭长方形
roundtooth:波浪形边框 1
sawtooth:波浪形边框 2
square:长方形
这里设置在坐标(1,1)上,即文字下面y=sinx的蓝色字段 使用方法:plt.legeng() 图例在图中的地理位置:
best
upper right
upper left
lower left
lower right
right
center left
center right
lower center
upper center
center plt.table(cellText=None, cellColours=None, cellloc='right' ,colWidths=None,
rowLabels=None,
rowColours=None,
collLabels=None,
colColours=None,
collloc='center', loc='bpttpm', bbox=None, edges='closed', **kwargs) cellText:表格单元格文本。类型为二维字符串列表
cellColours:表格单元格背景色。类型为二位颜色值列表
cellloc:表格单元格文本的对齐方式。默认值为right colWidths:表格单元格宽度。类型为浮点数列表
rowLabels:表格行表头文本。类型为字符串列表
rowColours:表格行表头背景色。类型为颜色列表
colLabels:表格列表头文本。类型为字符串列表
colLoc:表格行表头文本对齐方式。默认 right colColours:表格列表头背景色。类型为颜色列表
loc:单元格相对于子图的位置
bbox:绘制表格的边界框,如果此参数不为 None,将会覆盖 loc 参数
edges:单元格边线,该属性会影响各类单元格背景色 这串代码用于显示中文字符 无论画什么图,最后都得使用plt.show()用于展示图片,否则输出为空 【相关推荐:Python3视频教程 】plt.annotate('local',
xy=(2, 1),
xytext=(0.5, 0.5),
weight='bold',
color='red',
xycoords="data",
arrowprops=
dict(arrowstyle="->", connectionstyle='arc3', color='b'),
bbox=
dict(boxstyle="rarrow",
pad=0.6,
fc="yellow",
ec='k',
lw=1,
alpha=0.5)
)

2.9 bbox:给标题增加外框
2.10 . text():添加图形内容细节的无指向型注释文本(水印)
plt.text(1, 1,
"y=sinx",
weight='bold',
color ='b')

2.11. title():添加图形内容的标题
plt.title("正弦函数")

2.12. legend():标示不同图形的文本标签图例
plt.legend(loc="lower left") # 设置图例位置

2.13 table():向子图中添加表格
3. 完整代码显示
import matplotlib.pyplot as plt
import numpy as np
plt.figure(figsize=(10, 10))
x = np.linspace(0.05, 10, 1000) # 在0.05到10的区间中,等差选取1000个,端点不属于
y = np.sin(x)
plt.rcParams['font.sans-serif'] = ['SimHei']
plt.rcParams['axes.unicode_minus'] = False
plt.plot(x, y,
color='red',
ls='-',
label='sinx')
plt.xlim(1, 10)
plt.ylim(-1, 1)
plt.xlabel('x轴')
plt.ylabel('y轴')
plt.grid(ls=':',
color='blue') # 设置网格,颜色为蓝色
plt.axhline(0.5, color='green', lw=2, label="分割线") # 绘制平行于x轴的水平参考线,绿色,名称
plt.axvspan(xmin=2,
xmax=5,
facecolor='r',
alpha=0.2) # 绘制垂直于x轴的参考区域
plt.axhspan(ymin=(-3**0.5)/2,
ymax=(3**0.5)/2,
facecolor='w',
alpha=0.2)
plt.legend(loc="lower left") # 设置图例位置
plt.annotate('local',
xy=(2, 1),
xytext=(0.5, 0.5),
weight='bold',
color='red',
xycoords="data",
arrowprops=
dict(arrowstyle="->", connectionstyle='arc3', color='b'),
bbox=
dict(boxstyle="rarrow",
pad=0.6,
fc="yellow",
ec='k',
lw=1,
alpha=0.5)
)
plt.xticks(list(range(0, 12, 1))) # 调整刻度范围和刻度标签
plt.text(1, 1,
"y=sinx",
weight='bold',
color ='b')
plt.title("正弦函数")
plt.show()
plt.rcParams['font.sans-serif'] = ['SimHei']
plt.rcParams['axes.unicode_minus'] = False
4.折线图的线条风格
-:实线样式
--:短横线样式
-.:点划线样式
::虚线样式
.:点标记
O:圆标记
V:倒三角标记
^:正三角标记
:右三角表示
1:下箭头标记13
2:上箭头标记
3:左箭头标记
4:右箭头标记
S:正方形标记
p:五边形标记
*:星形标记
H:六边形标记
+:加号标记
X:x 标记
D:菱形标记
|:竖直线标记
_:水平线标记
5. 常用颜色缩写
b 蓝色
g 绿色
r 红色
c 青色
m 品红色·
y 黄色
k 黑色
w 白色
The above is the detailed content of Detailed explanation of the basic parameters of matplotlib.pyplot in Python visualization summary. For more information, please follow other related articles on the PHP Chinese website!
Python vs. C : Learning Curves and Ease of UseApr 19, 2025 am 12:20 AMPython is easier to learn and use, while C is more powerful but complex. 1. Python syntax is concise and suitable for beginners. Dynamic typing and automatic memory management make it easy to use, but may cause runtime errors. 2.C provides low-level control and advanced features, suitable for high-performance applications, but has a high learning threshold and requires manual memory and type safety management.
Python vs. C : Memory Management and ControlApr 19, 2025 am 12:17 AMPython and C have significant differences in memory management and control. 1. Python uses automatic memory management, based on reference counting and garbage collection, simplifying the work of programmers. 2.C requires manual management of memory, providing more control but increasing complexity and error risk. Which language to choose should be based on project requirements and team technology stack.
Python for Scientific Computing: A Detailed LookApr 19, 2025 am 12:15 AMPython's applications in scientific computing include data analysis, machine learning, numerical simulation and visualization. 1.Numpy provides efficient multi-dimensional arrays and mathematical functions. 2. SciPy extends Numpy functionality and provides optimization and linear algebra tools. 3. Pandas is used for data processing and analysis. 4.Matplotlib is used to generate various graphs and visual results.
Python and C : Finding the Right ToolApr 19, 2025 am 12:04 AMWhether to choose Python or C depends on project requirements: 1) Python is suitable for rapid development, data science, and scripting because of its concise syntax and rich libraries; 2) C is suitable for scenarios that require high performance and underlying control, such as system programming and game development, because of its compilation and manual memory management.
Python for Data Science and Machine LearningApr 19, 2025 am 12:02 AMPython is widely used in data science and machine learning, mainly relying on its simplicity and a powerful library ecosystem. 1) Pandas is used for data processing and analysis, 2) Numpy provides efficient numerical calculations, and 3) Scikit-learn is used for machine learning model construction and optimization, these libraries make Python an ideal tool for data science and machine learning.
Learning Python: Is 2 Hours of Daily Study Sufficient?Apr 18, 2025 am 12:22 AMIs it enough to learn Python for two hours a day? It depends on your goals and learning methods. 1) Develop a clear learning plan, 2) Select appropriate learning resources and methods, 3) Practice and review and consolidate hands-on practice and review and consolidate, and you can gradually master the basic knowledge and advanced functions of Python during this period.
Python for Web Development: Key ApplicationsApr 18, 2025 am 12:20 AMKey applications of Python in web development include the use of Django and Flask frameworks, API development, data analysis and visualization, machine learning and AI, and performance optimization. 1. Django and Flask framework: Django is suitable for rapid development of complex applications, and Flask is suitable for small or highly customized projects. 2. API development: Use Flask or DjangoRESTFramework to build RESTfulAPI. 3. Data analysis and visualization: Use Python to process data and display it through the web interface. 4. Machine Learning and AI: Python is used to build intelligent web applications. 5. Performance optimization: optimized through asynchronous programming, caching and code
Python vs. C : Exploring Performance and EfficiencyApr 18, 2025 am 12:20 AMPython is better than C in development efficiency, but C is higher in execution performance. 1. Python's concise syntax and rich libraries improve development efficiency. 2.C's compilation-type characteristics and hardware control improve execution performance. When making a choice, you need to weigh the development speed and execution efficiency based on project needs.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Atom editor mac version download
The most popular open source editor

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.




xlim() and ylim():Set the numerical display range of x and y axes


