目录
0 matplotlib 官方文档查询最直接/权威
0.1 官方文档
0.2 plt 画图的特别备注:避免乱码负号等问题
0.2.1 注意乱码问题解决
0.2.2 注意python的代码大小写
1 matplotlib的基本用法 (画图流程)
1.1 需要用到的模块,需要实现安装,且导入
1.1.1 导入 import matplotlib.pyplot
1.1.2 matplotlib 词源
1.2 figure 画图容器/ 画布
1.2.1 figure的官方解释
1.2.2 必须先获取至少1个figure:
1.2.3 多个figure存在时,figure的生效范围
1.2.4 因为可以一段代码里存在多个plt.figure(),因此可以设置多个画布
1.2.5 画布语法
1.3 设置函数图形
1.3.1 常规的函数设定方式
1.3.2 用x,y 分别是离散的散点数组,plt.plot() 也可以根据散点画图
1.4 绘图 plt.plot()
1.4.1 plt.plot()的语法
1.5 显示图像 plt.show()
1.5.1 关于 plt.show() 到底是否需要,用jupyter来写py实测并不需要plt.show()
1.6 用plt.plot 画出一个函数图形,测试代码
2 画布和图形的层级
3 画布的各种设定
3.1 关于颜色的设定
3.1.1 颜色的写法
3.1.2 修改颜色代码例子
3.2 设置画布的图形标题
编辑
3.3 图片的图例
3.3.1 用plt.legend() 可设置多个曲线的图例,且默认展示在一起。
3.3.2 plt.plot(lable="")也可以设置单个plot 曲线的label,和图例效果差不多
3.3.3 如何设置图例 plt.legend()
3.3.4 可用的 plt.legend(loc="") 属性
3.3.5 测试图例 plt.legend()代码
3.4 是否显示网格
4 关于坐标轴的各种设置
4.1 坐标轴的描述
4.2 坐标轴范围设置
4.3 坐标轴的刻度设置
4.3.1 设置坐标轴刻度:用数组,或者其他类linspace()都可以
4.3.2 清除刻度
4.3.3 把数字刻度--标记为文本标签 label的显示形式
4.3.4 如果在label="" 包含中文时出现乱码,在block开头加如下代码即可
4.4 显示文本注释: ()
4.4.1 语法
4.4.2 测试代码
4.5 显示箭头+文本注释: plt.annotate()
4.5.1 语法
4.5.2 测试代码
4.6 图形间填充
4.6.1 语法
4.6.2 测试代码
5 边界spines 和 移动坐标轴
5.1 先获取坐标轴
5.2 图片的4边,都是spine
5.3 比如隐藏右边、上边的spine
5.4 移动两个spine到0,0 点,达到把坐标轴移动的目的
5.5 移动坐标轴的代码(可看出坐标pos(0,0)处有了我们熟悉的数学坐标轴!)
5.5.1 移动效果看下面的图
5.5.2 移动坐标轴前后对比的测试代码
5.6 一个警告,不是报错
5.6.1 警告出现的可能原因1
5.6.2 警告出现的可能原因2
6 保存图片 plt.savefig()
6.1 详细语法
6.2 测试保存代码
MatplotlibMatplotlib中文网、Matplotlib官方中文文档。/
教程 | MatplotlibMatplotlib中文网、Matplotlib官方中文文档。
matplotlib.pyplot.axes — Matplotlib 3.8.2 documentation.pyplot.axes.html
- 一般加在一段代码block的最前面
import numpy as np
import matplotlib.pyplot as plt
matplotlib 推测词源
figure是一顶级的容器,包含了绘图所有的元素。我把这个理解为画布
画布语法:figure(num=None, figsize=None, dpi=None, facecolor=None, edgecolor=None, frameon=True)
plt.subplot() 可以看到figure的编号
import numpy as np
import matplotlib.pyplot as pltfig1=plt.figure("名字",figsize=None,dpi=None,facecolor="gray", edgecolor="white", frameon=True)x=np.linspace(-5,5, 10)
y=x*2+1
y2=x**2# 绘图
plt.plot(x, y)
plt.plot(x, y2)# 显示图像
plt.show()
设置函数的关键:
函数就是形如 y=f(x)的样式,但是函数的作图需要具体的数据。
比如 这样也可以生成函数,和函数图形
- x=[1,2,3,4,5]
- y=[2,4,6,8,10]
plt.plot(x,y)
下面是测试的代码
import numpy as np
import matplotlib.pyplot as pltx=[1,2,3,4,5]
y=[2,4,6,8,10]plt.figure
plt.plot(x,y,c="#000000")plt.show
matplotlib
作图,要显示图像,必须调用plt.show()
, 否则不显示plt.show()也能正常显示
%matplotlib notebook
%matplotlib inline
import numpy as np
import matplotlib.pyplot as pltplt.figure(figsize=(3,3))
plt.plot([2,4,6,8,10])
plt.show()
import numpy as np
import matplotlib.pyplot as pltplt.figure(figsize=(3,3))
plt.plot([2,4,6,8,10])
import numpy as np
import matplotlib.pyplot as plt%matplotlib notebook
%matplotlib inlineplt.figure(figsize=(3,3))
plt.plot([2,4,6,8,10])
import numpy as np
import matplotlib.pyplot as pltplt.plot(s(x),color = 'r', # 线条颜色linewidth = 2, # 线条宽度 linestyle='-.', # 线的类型:虚线:'--',点线:'-.',短虚线':',实线:'-'marker='*', # 线上点的形状markersize = 5, # 点的大小markeredgecolor = 'b', # 点的边框颜色markerfacecolor ='green', # 点的背景颜色,可能因为点太小没显示出来?label = 'cos', # 图例alpha = 1 ) # 透明度:0-1之间 ,默认1plt.legend(fontsize = 15) # 显示图例
plt.show()
1、axes:axes包含定义单元集的Axis对象。
2、axis:axis是指定图表中所有baiAxes对象的组成部分。
matplotlib.pyplot.axis(*v, **kwargs)
获得或设定axis内容的便利方法。
常用参数:
xmin, ymin, xmax, ymax : float, optional
The axis limits to be set. Either none or all of the limits must be given.
option : str
Possible values:
Value Description
‘on’ Turn on axis lines and labels.
‘off’ Turn off axis lines and labels.
‘equal’ Set equal scaling (i.e., make circles circular) by changing axis limits.
‘scaled’ Set equal scaling (i.e., make circles circular) by changing dimensions of the plot box.
‘tight’ Set limits just large enough to show all data.
‘auto’ Automatic scaling (fill plot box with data).
‘normal’ Same as ‘auto’; deprecated.
‘image’ ‘scaled’ with axis limits equal to data limits.
‘square’ Square plot; similar to ‘scaled’, but initially forcing xmax-xmin = ymax-ymin.emit : bool, optional, default True
Whether observers are notified of the axis limit change. This option is passed on to set_xlim andset_ylim.
matplotlib.pyplot.axes(arg=None, **kwargs)
在当前figure新增一个axes对象,并设为当前活动。
axes不是数学上的座标轴,而是图形结构中的一个对象。所有绘图函数都是直接作用在当前axes对象上。
常用参数:
arg : { None, 4-tuple, Axes }
The exact behavior of this function depends on the type:
None: A new full window axes is added using subplot(111, **kwargs)
4-tuple of floats rect = [left, bottom, width, height]. A new axes is added with dimensions rect in normalized (0, 1) units using add_axes on the current figure.
Axes: This is equivalent to pyplot.sca. It sets the current axes to arg. Note: This implicitly changes the current figure to the parent of arg.
Note
projection : {None, ‘aitoff’, ‘hammer’, ‘lambert’, ‘mollweide’, ‘polar’, ‘rectilinear’, str}, optional
The projection type of the Axes. str is the name of a costum projection, see projections. The default None results in a ‘rectilinear’ projection.
polar : boolean, optional
If True, equivalent to projection=‘polar’.
sharex, sharey : Axes, optional
Share the x or y axis with sharex and/or sharey. The axis will have the same limits, ticks, and scale as the axis of the shared axes.
label : str
A label for the returned axes.
import numpy as np
import matplotlib.pyplot as pltx=np.linspace(-10,10,100)plt.figure
plt.plot(x,np.sin(x),c="b")plt.show
import numpy as np
import matplotlib.pyplot as pltx=np.linspace(-10,10,100)plt.figure
plt.plot(x,np.sin(x),c="#000000")plt.show
显示要求
可以通过设置 loc=""属性,设置图例显示的位置,默认在左上角 upper left
可设置legend的位置
best
upper right
upper left
lower left
lower right
right
center left
center right
lower center
upper center
center
import numpy as np
import matplotlib.pyplot as pltx=[1,2,3,4,5]
y=[2,4,6,8,10]
y2=[z**2 for z in x]plt.figure
plt.plot(x,y,c="#000000",label="2x")
plt.plot(x,y2,label="x^2")plt.legend() # 如果不加这句 plt.legend() ,plot(label="")不会显示,默认在左上角
plt.legend(loc="lower right")plt.show
import numpy as np
import matplotlib.pyplot as pltfig1=plt.figure(num=1)x=np.linspace(-5,5, 10)
y=x*2+1
y2=x**2# 设置坐标轴描述
plt.xlabel("X axis")
plt.ylabel("Y axis")# 设置坐标轴范围
plt.xlim((-10,10))
plt.ylim((-10,10))# 设置坐标轴刻度
icks([-4, -2, 0, 2, 4])
icks(np.linspace(-10, 10, 10))
# 这样可以清除刻度 icks()
# 这样可以清除刻度 icks()# 绘图
plt.plot(x, y)
plt.plot(x, y2)# 显示图像
plt.show()
import numpy as np
import matplotlib.pyplot Params['font.family']='LiSu'# 正常显示中文
Params['axes.unicode_minus']=False# 正常显示负号x=np.linspace(-10,10,100)plt.figure
plt.plot(x,np.sin(x),c="#000000")icks([-10,-5,0,5,10],['巴黎','北京','纽约','伦敦','悉尼'])
# 这样也可以 icks([-10,-5,0,5,10],labels=['巴黎','北京','纽约','伦敦','悉尼'])
icks([-1,-0.5,0,0.5,1],labels="ABCDE")plt.show
Params['axes.unicode_minus']=False# 正常显示负号
<(x =pos,y = pos, s = '这是标注', fontsize = 15,c = 'b',rotation = 20)
import numpy as np
import matplotlib.pyplot as pltx=[1,2,3,4,5]
y=[2,4,6,8,10]
y2=[z**2 for z in x]plt.figure
plt.plot(x,y,c="#000000",label="2x")
plt.plot(x,y2,label="x^2")plt.legend() # 如果不加这句 plt.legend() ,plot(label="")不会显示,默认在左上角
plt.legend(loc="lower right")(x=3,y=6,s="这是2y",fontsize = 20,c = 'b',rotation = 15)
(x=3,y=10,s="这是y^2",fontsize = 20,c = 'r',rotation = 50)#plt.savefig(r"C:UsersAdministratorDesktop测试函数图片101.jpg")plt.show
plt.annotate(text,xy,xytext,arrowprops)
import numpy as np
import matplotlib.pyplot as pltx=[1,2,3,4,5]
y=[2,4,6,8,10]
y2=[z**2 for z in x]plt.figure
plt.plot(x,y,c="#000000",label="2x")
plt.plot(x,y2,label="x^2")plt.legend() # 如果不加这句 plt.legend() ,plot(label="")不会显示,默认在左上角
plt.legend(loc="lower right")(x=3,y=6,s="这是2y",fontsize = 20,c = 'b',rotation = 15)
(x=3,y=10,s="这是y^2",fontsize = 20,c = 'r',rotation = 50)plt.annotate(text = '相交点',xy = (2,4),xytext = (2,10),arrowprops = {'headwidth':10,'facecolor':'r'},fontsize = 15)#plt.savefig(r"C:UsersAdministratorDesktop测试函数图片101.jpg")plt.show
import numpy as np
import matplotlib.pyplot as pltx=[1,2,3,4,5]
y=[2,4,6,8,10]
y2=[z**2 for z in x]plt.figure
plt.plot(x,y,c="#000000",label="2x")
plt.plot(x,y2,label="x^2")plt.legend() # 如果不加这句 plt.legend() ,plot(label="")不会显示,默认在左上角
plt.legend(loc="lower right")(x=3,y=6,s="这是2y",fontsize = 20,c = 'b',rotation = 15)
(x=3,y=10,s="这是y^2",fontsize = 20,c = 'r',rotation = 50)plt.annotate(text = '相交点',xy = (2,4),xytext = (2,10),arrowprops = {'headwidth':10,'facecolor':'r'},fontsize = 15)
plt.fill_between(x,y,y2,facecolor = 'k',alpha = 0.2)#plt.savefig(r"C:UsersAdministratorDesktop测试函数图片101.jpg")plt.show
import numpy as np
import matplotlib.pyplot as plt#原始的
figure = plt.figure(num=99)
# x,y
x = np.linspace(-4, 4, 50)
y = x ** 2 - 4
xx_label = r"y = x ^ 2 - 4"
x_label = r"y = x"
plt.title("here is title")# 绘图
plt.plot(x, y, color="#ff0000",label="xxx")
# 显示图例
plt.legend()
plt.plot(x, x)
# 显示网格
id(True)
# 显示图例
plt.legend(labels=[xx_label, x_label])# 移动坐标轴的第2个图
figure = plt.figure(num=100)# x,y
x = np.linspace(-4, 4, 50)
y = x ** 2 - 4# 获取到坐标轴
ax = a()# 隐藏右边、上边的spine
ax.spines["right"].set_color("none")
ax.spines["top"].set_color("none")# 移动两个spine到0,0,达到把坐标轴移动的目的
ax.spines["bottom"].set_position(("data", 0))
ax.spines["left"].set_position(("data", 0))xx_label = r"y = x ^ 2 - 4"
x_label = r"y = x"
plt.title("here is title")# 绘图
plt.plot(x, y, color="#ff0000",label="xxx")# 显示图例
plt.legend()plt.plot(x, x)# 显示网格
id(True)# 显示图例
plt.legend(labels=[xx_label, x_label])plt.show()
运行代码时可能会出现如下警告:No artists with labels found to put in legend. Note that artists whose label
#plt.plot() 相关代码中缺乏label名称的说明
- plt.plot(x, y, color="#ff0000")
- plt.plot(x, y, color="#ff0000",label="xxx") #没有这个就会警告 label="xxx"
#legend相关代码中缺乏label名称的说明,需要给予图例对应的名字
- # 显示图例
- plt.legend()
- plt.legend(labels=[xx_label, x_label]) # 调整后不报错并显示图例
plt.savefig(fname, dpi=None, facecolor='w', edgecolor='w')
import numpy as np
import matplotlib.pyplot as pltx=[1,2,3,4,5]
y=[2,4,6,8,10]
y2=[z**2 for z in x]plt.figure
plt.plot(x,y,c="#000000",label="2x")
plt.plot(x,y2,label="x^2")plt.legend() # 如果不加这句 plt.legend() ,plot(label="")不会显示,默认在左上角
plt.legend(loc="lower right")plt.savefig(r"C:UsersAdministratorDesktop测试函数图片101.jpg")plt.show
本文发布于:2024-02-01 04:03:28,感谢您对本站的认可!
本文链接:https://www.4u4v.net/it/170673141133717.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
留言与评论(共有 0 条评论) |