首先导入相关库
import matplotlib.pyplot as plt
import numpy as np
(一)简单的作图
plt.plot([1,2,3,4])
plt.show()
当参数只有一个行列式的时候,plot(x,y)默认为y,x轴则从0开始

也可以分别定义x与y
x = np.linspace(0,10,100)
#linspace()从0开始到10,进行100等分
y = np.sin(x)
plt.plot(x,y)
plt.show()

?(二)在图中设定名称
在途中进行名称的设置可以在比较的时候更方便
x = np.linspace(0,10,100)
plt.plot(x,np.sin(x))
plt.title('Y=sin(X)')
plt.xlabel('X')
plt.ylabel('Y')
plt.show()

(三)更加精细的刻度的使用
x = np.linspace(0,2*np.pi)
plt.plot(x,np.sin(x))
plt.title('Title')
plt.grid(True)
#根据版本不同默认参数可能会改变,True为使用网格
positions = [0,np.pi/2,np.pi,np.pi*3/2,np.pi*2]
labels = ['0','90','180','270','360']
plt.xticks(positions,labels)
#plt.xticks(表示的位置,相对应的标签)
plt.show()

?(四)图的尺寸设置
当你觉得输出的图形看不清楚的时候,可以使用这个来调整图形的尺寸大小
plt.figure(figsize=(4,4))
#plt.figure(figsize=(横向尺寸,纵向尺寸))
x = np.linspace(0,2*np.pi)
plt.plot(x,np.sin(x))
plt.show()

??(五)散布图
当需要将多数个图进行比较的时候,可以使用subplot()
x = np.random.rand(100)
y = np.random.rand(100)
#随机生成100以内的数字
plt.subplot(221)
#plt.subplot()括号中总共三个参数,第一个参数表示行数,第二个表示列数,第三个表示从左上开始的位置
plt.scatter(x,y,s=600,c="pink",alpha=0.5,linewidths="2",edgecolors="red")
#s点的尺寸,c颜色,alpha透明度,linewidths描点的粗细,edgecolors周围线的颜色
plt.subplot(222)
plt.scatter(x,y,s=300,c="white",alpha=0.5,linewidths="2",edgecolors="yellow")
plt.subplot(223)
plt.scatter(x,y,s=300,c=y,cmap="Greens")
plt.subplot(224)
plt.scatter(x,y,s=300,c=y,cmap="Blues")
plt.show()

?(六)三次元散布图
三次元的散布图比二次元多一个参数z
np.random.seed(0)
random_x = np.random.randn(100)
random_y = np.random.randn(100)
random_z = np.random.randn(100)
fig=plt.figure(figsize=(8,8))
ax=fig.add_subplot(1,1,1,projection="3d")
x = np.ravel(random_x)
y = np.ravel(random_y)
z = np.ravel(random_z)
ax.scatter3D(x,y,z)
plt.show()

以上就是matplotlib()相关基础使用方法的介绍,如果有添加可以随时补充
|