Matplotlib.pyplot详解
1.matplotlib figure浅解
matplotlib figure中通常包含几个重要的组成部分:Title(figure的标题),Legend(图例),Grid(网格点),Axes(类似于区域),Axis(坐标轴),tick(坐标轴标记号),line(线),marker(点)等。
2.各组成部分用法
2.1 生成figure及Axes
import matplotlib.pyplot as plt
fig = plt.figure() # 生成无axes区域的空白图
plt.show()
fig, ax = plt.subplots() # 生成有一个axes区域的图
plt.show()
fig, axs = plt.subplots(2, 2) # 生成有2*2个axes区域的图
plt.show()
2.2 figure 及Axes 相关设置
2.2.1 figure 的 设置
figure 的设置包括设置 title , xlabel , ylabel , legend等,均用 plt.+设置对象即可
import matplotlib.pyplot as plt
fig = plt.figure() # 生成无axes区域的空白图
x=[1,2,3,4]
y1=[1,2,3,4]
y2=[5,6,7,8]
plt.plot(x,y1,x,y2)
plt.title("test")#设置标题
plt.xlabel("testX")#设置x轴的标题
plt.ylabel("testY")#设置y轴的标题
plt.legend(["1","2"])#多个图例时,要将各图例名称放在list列表中
plt.show()
2.2.2 Axes 的 设置
Axes作为区域还包含坐标轴Axis(x,y for 2D ; x,y,z for 3D),因此有set_title, set_xlabel, set_ylabel等设置,
import matplotlib.pyplot as plt
x=[1,2,3,4]
y1=[1,2,3,4]
y2=[5,6,7,8]
fig,axs = plt.subplots(2,2) # axs为2*2的array,包含四个Axes区域
#在第一个区域上画图并设置
axs[0,0].plot(x,y1)
axs[0,0].set_title("axs1")
axs[0,0].set_xlabel("x1")
axs[0,0].set_ylabel("y1")
#在第二个区域上画图并设置
axs[0,1].plot(x,y2)
axs[0,1].set_title("axs2")
axs[0,1].set_xlabel("x2")
axs[0,1].set_ylabel("y2")
plt.show()
2.3 线与点的生成及相关属性设置
import matplotlib.pyplot as plt
import numpy as np
x=np.linspace(-3,3,100)
y=np.sin(x)
plt.plot(x,y)#生成平滑曲线
#在生成曲线的函数中添加生成形式也可以,例如“*”等
#color="red"直接设置颜色
#LineWidth设置线宽
plt.plot(x,y,"*",color="red",LineWidth=3)
或者直接用生成散点图的函数plt.scatter
plt.scatter(x,y)#生成散点图