9.1matplotlib API入门
#简单图形创建
import numpy as np
import matplotlib.pyplot as plt
data=np.arange(10)
data
array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
plt.plot(data)
[<matplotlib.lines.Line2D at 0x1dc96438cd0>]
#创建figure
fig=plt.figure()
#创建子图
ax1=fig.add_subplot(2,2,1)#创建4个图,位置第一个
ax2=fig.add_subplot(2,2,2)
ax3=fig.add_subplot(2,2,3)
ax3.plot(np.random.randn(50).cumsum(),'k--')
ax1.hist(np.random.randn(100),bins=20,color='b',alpha=0.2)
ax2.scatter(np.arange(30),np.arange(30)+3*np.random.randn(30))
<matplotlib.collections.PathCollection at 0x1dc96c17310>
#使用plt.subplots创建子图
fig,axes=plt.subplots(2,2,sharex=True,sharey=True)#axes是画图区域,figure是更大的画布
for i in range(2):
for j in range(2):
axes[i,j].hist(np.random.randn(500),bins=50,color='r')
plt.subplots_adjust(wspace=0.1,hspace=0.1)#subplots_adjust用于调整子图
颜色、标记和线型
对于字符串格式,标记类型和线型必须放在颜色后面,如’ro–’
plt.subplots(1,1)
plt.plot(np.random.randn(30),'ro--')
#另一种形式
plt.plot(np.random.randint(0,3,100),'k^--')
plt.show()
#修改插值方式
data=np.random.randn(30).cumsum()
plt.subplots(1,1)
plt.plot(data,'bo--',label='default')
plt.plot(data,'yo--',drawstyle='steps-post',label='steps-post')
plt.legend(loc='best')
<matplotlib.legend.Legend at 0x1dc96faa340>
刻度、标签和图例
fig=plt.figure()
ax=fig.add_subplot(1,1,1)
ax.plot(np.random.randn(1000).cumsum())
#设置刻度
ticks=ax.set_xticks([0,250,500,750,1000]