赞
踩
目录
1.1.1 导入 import matplotlib.pyplot
1.2.4 因为可以一段代码里存在多个plt.figure(),因此可以设置多个画布
1.3.2 用x,y 分别是离散的散点数组,plt.plot() 也可以根据散点画图
1.5 显示图像 plt.show() 和 plt.imshow()
1.5.1 关于 plt.show() 到底是否需要,用jupyter来写py实测并不需要plt.show()
1.7 一个典型的报错 plt.plot(x,y1,x,y2) 可以同时画2个曲线
1.7.1 报错 TypeError: unsupported operand type(s) for ** or pow(): 'list' and 'int'
1.7.2 只要将 np.array([1,2,3,4,5]) 转化成 ndarray 就可以
1.7.3 用 np.linspace([1,2,3,4,5]) 等 ndarray类型也可以
1.7.4 用python 的list也可以,但是f(x) 也要修改为 list 也可以
1.7.5 用ndarrat配合,但是f(x) 也要修改为 list 也可以
1.8 plt.plot(x,y1,x,y2) 可以同时画2个曲线
2.1.1 plt.imread(fname, format=None)
2.2 可用plt.imread(path) 和 plt.imshow(pic)直接读入图片和显示图片
2.2.1 接前面的plt.imread(path),还可以把保存的图片再用 plt.imshow(图片) 再显示出来
2.4.2 设置坐标轴的label,比如ax.set_xticklabels()
2.4.3 设置坐标轴ax = plt.gca() 和 ax.spines["top"]
2.4.4 上述代码测试:plt.plot() 和 ax1.plot(2,3) 确实很像,分别针对全图/子图
B> fig,axes=plt.subplots(2,3)子图范围内
C> 尽量不要在ax1 等子图区域,生效范围内写plt.plot()等
2.5.1 fig.add_axes([left, bottom, width, height])
2.6.1 matplotlib.pyplot.axis(*v, **kwargs)
3.3.1 用plt.legend() 可设置多个曲线的图例,且默认展示在一起。
3.3.2 plt.plot(lable="")也可以设置单个plot 曲线的label,和图例效果差不多
3.3.4 可用的 plt.legend(loc="") 属性
4.3.1 设置坐标轴刻度:用数组,或者其他类linspace()都可以
4.3.3 把数字刻度--标记为文本标签 label的显示形式
4.3.4 如果在label="" 包含中文时出现乱码,在block开头加如下代码即可
5.4 移动两个spine到0,0 点,达到把坐标轴移动的目的
5.5 移动坐标轴的代码(可看出坐标pos(0,0)处有了我们熟悉的数学坐标轴!)
MatplotlibMatplotlib中文网、Matplotlib官方中文文档。https://www.matplotlib.org.cn/
- 一般加在一段代码block的最前面
- plt.rcParams['font.family']='LiSu'# 正常显示中文
- plt.rcParams['axes.unicode_minus']=False# 正常显示负号
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 plt
-
- fig1=plt.figure("名字",figsize=[5,5],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 plt
-
- x=[1,2,3,4,5]
- y=[2,4,6,8,10]
-
- plt.figure
- plt.plot(x,y,c="#000000")
-
- plt.show
'运行
- import numpy as np
- import matplotlib.pyplot as plt
-
- plt.rcParams['font.family']='LiSu'# 正常显示中文
- plt.rcParams['axes.unicode_minus']=False# 正常显示负号
-
-
- fig=plt.figure("画布1",figsize=[5,5],dpi=None,facecolor="gray", edgecolor="red", frameon=True)
-
- x=np.linspace(-10,10,100)
- plt.plot(x,x**2,
- linestyle="-",
- linewidth=3,
- color="red",
- scalex=True, #默认是true,画布和axis 受到数据的约束
- scaley=True,
- marker="*",
- markersize=1,
- markeredgecolor="black",
- markerfacecolor='brown',
- label="y=x^2",
- alpha=0.5)
- #有些属性可以合并为 比如 'ro' red的o点形态
- plt.legend()
- plt.show
'运行
matplotlib
作图,要显示图像,必须调用plt.show()
, 否则不显示plt.show()也能正常显示,测试并不成功
%matplotlib notebook
%matplotlib inline
- import numpy as np
- import matplotlib.pyplot as plt
-
- plt.plot(x,
- np.cos(x),
- color = 'r', # 线条颜色
- linewidth = 2, # 线条宽度
- linestyle='-.', # 线的类型:虚线:'--',点线:'-.',短虚线':',实线:'-'
- marker='*', # 线上点的形状
- markersize = 5, # 点的大小
- markeredgecolor = 'b', # 点的边框颜色
- markerfacecolor ='green', # 点的背景颜色,可能因为点太小没显示出来?
- label = 'cos', # 图例
- alpha = 1 ) # 透明度:0-1之间 ,默认1
-
- plt.legend(fontsize = 15) # 显示图例
- plt.show()

TypeError: unsupported operand type(s) for ** or pow(): 'list' and 'int'
- import numpy as np
- import pandas as pd
- import matplotlib.pyplot as plt
-
- x=[1,2,3,4,5]
- print(type(x))
- y1=2*x #不能写成y1=2x
- y2=x**2
-
- plt.plot(x,y1,x,y2)
- plt.show()
- import numpy as np
- import pandas as pd
- import matplotlib.pyplot as plt
-
- x=np.array([1,2,3,4,5])
- print(type(x))
- y1=2*x #不能写成y1=2x
- y2=x**2
-
- plt.plot(x,y1,x,y2)
- plt.show()
- import numpy as np
- import pandas as pd
- import matplotlib.pyplot as plt
-
- x=np.linspace(-5,5,10)
- print(type(x))
- y1=2*x #不能写成y1=2x
- y2=x**2
-
- plt.plot(x,y1,x,y2)
- plt.show()
'运行
X=[1,2,3]
print(type(x))
y1=[2*x for x in X]
y2=[x**2 for x in X]
- import numpy as np
- import pandas as pd
- import matplotlib.pyplot as plt
-
- X=[1,2,3]
- print(type(x))
- y1=[2*x for x in X]
- y2=[x**2 for x in X]
-
- plt.plot(X,y1,X,y2) #此时X不可省略,x是错的,必须用X才是ndarray
- plt.show()
'运行
- import numpy as np
- import pandas as pd
- import matplotlib.pyplot as plt
-
- X=np.array([1,2,3])
- print(type(x))
- y1=[2*x for x in X]
- y2=[x**2 for x in X]
-
- plt.plot(X,y1,X,y2) #此时X不可省略,x是错的,必须用X才是ndarray
- plt.show()
path1=r"C:\Users\Administrator\Desktop\tp2.jpg"
pic1=plt.imread(path1, format=None)
print(type(pic1))
print(pic1)
plt.imshow(pic1)
以上内容的测试过程和结果如下
- import numpy as np
- import matplotlib.pyplot as plt
-
- path1=r"C:\Users\Administrator\Desktop\tp2.jpg"
- pic1=plt.imread(path1, format=None)
- print(type(pic1))
- print(pic1)
-
- fig=plt.figure
- plt.imshow(pic1)
除了格子特定的语法,还可以通过设置子区域ax的属性来设置那些属性
fig,axes=plt.subplots(2,2)
ax1=axes[0,0]
# 子图1,散点图
ax1.scatter(np.linspace(-2, 2, 5), np.random.randn(5))
ax.set_xticklabels()
比如 ax.set_xticklabels()
和 ax.set_yticklabels()
设置每个刻度对应的标签。
fig, ax = plt.subplots(1)
ax.plot(x_label, x_label*2)
# 设置 y 轴刻度名称
ax.set_yticks(range(0,8,2))
ax.set_yticklabels(['Forth', 'Third', 'Second', 'First'])
plt.show()
- # 获取坐标轴,gca就是get current axes的意思
- ax = plt.gca()
- 图片的4边,都是spine
- 可以通过plt.gca().spines 分别操作这4个spine
- ax.spines["top"]
- ax.spines["bottom"]
- ax.spines["right"]
- ax.spines["left"]
- #定义全图区域
- fig= plt.figure()
- #设置全图
- plt.plot(x, x**2)
- #设置全图的轴
- plt.gca().spines[]
- #设置全图的轴的内容
- plt.xticks()
- #定义子图区域
- fig,axes=plt.subplots(2,3)
- ax1=axes[0,0]
- #设置子图
- ax1.plot(x, x**2)
- #设置子图的轴
- ax1.spines[]
- #设置子图的轴的内容
- ax1.set_yticks(range(0,20,4))
下面是详细代码
- import numpy as np
- import matplotlib.pyplot as plt
-
- #---------------第1部分内容---------------
- #第1部分内容,第1个figure生效范围
- x=np.linspace(-5, 5, 10)
- plt.plot(x, x**1)
- plt.xticks([-5,-2,0,2,5],labels=["A","B","C","D","E"])
-
- ax = plt.gca()
- ax.spines["right"].set_color("none")
- plt.gca().spines["top"].set_color("none")
- ax.spines["bottom"].set_position(("data", 0))
- plt.gca().spines["left"].set_position(("data", 0))
-
- #因为ax = plt.gca() 所以ax.plot()画的图形还是会显示在第一个figure内
- ax.plot(x, x**2)
-
-
- #---------------第2部分内容---------------
- #第2部分内容,第2个figure且倍分割为子图区域
-
- fig,axes=plt.subplots(2,3)
- ax1=axes[0,0]
- # 子图1,散点图
- ax1.plot(x, x**2)
- ax1.set_yticks(range(0,20,4))
- ax1.set_yticklabels(['First','Second','Third', 'Forth', 'Fifth'])
- ax1.spines["right"].set_color("none")
- ax1.spines["top"].set_color("none")
- ax1.spines["bottom"].set_position(("data", 0))
- ax1.spines["left"].set_position(("data", 0))
-
- ax2=axes[0,1]
- # 子图1,散点图
-
- #plt.开头的如果在fig,axes=plt.subplots(2,3) 后,会默认作图在最后一个子图里,而不是完整的大图
- #因此不适合在ax2 等子区域内做 plt.plot() 等整图设置
- plt.plot(x, x**2)
- plt.yticks(range(0,20,4),['First','Second','Third', 'Forth', 'Fifth'])
-
- ax = plt.gca()
- ax.spines["right"].set_color("none")
- ax.spines["top"].set_color("none")
- ax.spines["bottom"].set_position(("data", 0))
- ax.spines["left"].set_position(("data", 0))
- ax.plot(x, x**2)
-
-
- #---------------第3部分内容---------------
- #第3部分内容,第3个figure
- fig3=plt.figure()
- plt.plot(x, x**2)
- plt.yticks(range(0,20,4),['First','Second','Third', 'Forth', 'Fifth'])
-
- ax = plt.gca()
- ax.spines["right"].set_color("none")
- ax.spines["top"].set_color("none")
- ax.spines["bottom"].set_position(("data", 0))
- ax.spines["left"].set_position(("data", 0))
- ax.plot(x, x**2)

- import numpy as np
- import matplotlib.pyplot as plt
-
- fig=plt.figure(num=1,
- figsize=[5,5],
- dpi=None,
- facecolor="gray",
- linewidth=5,
- edgecolor="red",
- frameon=True)
-
- plt.title("测试图")
- #fig.add_axes([left, bottom, width, height])
- axes1=fig.add_axes([0,0,0.5,0.5],facecolor="green")
- axes2=fig.add_axes([0.4,0.4,0.3,0.3],facecolor="blue",sharex=axes1)
- plt.show()
'运行
**kwargs
- import numpy as np
- import matplotlib.pyplot as plt
-
- fig=plt.figure(num=1,
- figsize=[5,5],
- dpi=None,
- facecolor="gray",
- linewidth=5,
- edgecolor="red",
- frameon=True)
-
- plt.title("测试图")
- #fig.add_axes([left, bottom, width, height])
- axes1=fig.add_axes([0,0,0.5,0.5],facecolor="green")
- axes2=fig.add_axes([0.4,0.4,0.3,0.3],facecolor="blue",sharex=axes1)
-
- plt.plot([0,1,2,3,4,5],[0,1,4,9,16,25])
- plt.axis("on")
- plt.axis("equal")
-
-
- plt.show()
'运行
修改
plt.axis("on")
plt.axis("scaled")
也可以是复合写法:比如颜色线,点的复合控制字符串
比如下面的参数 'gd-.'
比如用 "ro" 表示red的o型
plt.plot(x_label, x_label*1., 'gd-.')
plt.show()
- import numpy as np
- import matplotlib.pyplot as plt
-
- x=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 plt
-
- x=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 plt
-
- x=[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 plt
-
- fig1=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))
-
- # 设置坐标轴刻度
- plt.xticks([-4, -2, 0, 2, 4])
- plt.yticks(np.linspace(-10, 10, 10))
- # 这样可以清除刻度 plt.xticks()
- # 这样可以清除刻度 plt.yticks()
-
- # 绘图
- plt.plot(x, y)
- plt.plot(x, y2)
-
- # 显示图像
- plt.show()
'运行
plt.yticks([-1,-0.5,0,0.5,1],labels="ABCDE")
- import numpy as np
- import matplotlib.pyplot as plt
-
- plt.rcParams['font.family']='LiSu'# 正常显示中文
- plt.rcParams['axes.unicode_minus']=False# 正常显示负号
-
- x=np.linspace(-10,10,100)
-
- plt.figure
- plt.plot(x,np.sin(x),c="#000000")
-
- plt.xticks([-10,-5,0,5,10],['巴黎','北京','纽约','伦敦','悉尼'])
- # 这样也可以 plt.xticks([-10,-5,0,5,10],labels=['巴黎','北京','纽约','伦敦','悉尼'])
- plt.yticks([-1,-0.5,0,0.5,1],labels="ABCDE")
-
- plt.show
'运行
plt.rcParams['font.family']='LiSu'# 正常显示中文
plt.rcParams['axes.unicode_minus']=False# 正常显示负号
plt.text(x =pos,y = pos, s = '这是标注', fontsize = 15,c = 'b',rotation = 20)
- import numpy as np
- import matplotlib.pyplot as plt
-
- x=[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.text(x=3,y=6,s="这是2y",fontsize = 20,c = 'b',rotation = 15)
- plt.text(x=3,y=10,s="这是y^2",fontsize = 20,c = 'r',rotation = 50)
-
-
- #plt.savefig(r"C:\Users\Administrator\Desktop\测试函数图片101.jpg")
-
- plt.show
'运行
plt.annotate(text,xy,xytext,arrowprops)
- import numpy as np
- import matplotlib.pyplot as plt
-
- x=[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.text(x=3,y=6,s="这是2y",fontsize = 20,c = 'b',rotation = 15)
- plt.text(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:\Users\Administrator\Desktop\测试函数图片101.jpg")
-
- plt.show
'运行
- import numpy as np
- import matplotlib.pyplot as plt
-
- x=[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.text(x=3,y=6,s="这是2y",fontsize = 20,c = 'b',rotation = 15)
- plt.text(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:\Users\Administrator\Desktop\测试函数图片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)
- # 显示网格
- plt.grid(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 = plt.gca()
-
- # 隐藏右边、上边的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)
-
- # 显示网格
- plt.grid(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 plt
-
- x=[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:\Users\Administrator\Desktop\测试函数图片101.jpg")
-
- plt.show
'运行
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。