刻度,标签和图例
plt的xlim、xticks和xtickslabels方法分别控制图表的范围和,刻度位置和刻度标签。
调用方法时不带参数,则返回当前的参数值;调用时带参数,则设置参数值。
plt.plot(np.random.randn(30),color='g',linestyle='--',marker='o')
plt.xlim() #不带参数调用,显示当前参数;
#可将xlim替换为另外两个方法试试
(-1.4500000000000002, 30.45)
plt.plot(np.random.randn(30),color='g',linestyle='--',marker='o')
plt.xlim([0,15]) #横轴刻度变成0-15
(0, 15)
设置标题,轴标签,刻度以及刻度标签
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]) #设置刻度值
labels = ax.set_xticklabels(['one','two','three','four','five']) #设置刻度标签
ax.set_title('My first Plot') #设置标题
ax.set_xlabel('Stage') #设置轴标签
Text(0.5,0,'Stage')
添加图例
图例legend是另一种用于标识图标元素的重要工具。 可以在添加subplot的时候传入label参数
fig = plt.figure(figsize=(12,5));ax = fig.add_subplot(111)
ax.plot(np.random.randn(1000).cumsum(),'k',label='one') #传入label参数,定义label名称
ax.plot(np.random.randn(1000).cumsum(),'k--',label='two')
ax.plot(np.random.randn(1000).cumsum(),'k.',label='three')
#图形创建完后,只需要调用legend参数将label调出来即可。
ax.legend(loc='best') #要求不是很严格的话,建议使用loc=‘best’参数来让它自己选择最佳位置
<matplotlib.legend.Legend at 0xa8f5a20>