用plot_date python改变ylim

时间:2016-07-20 00:00:09

标签: python matplotlib

我无法弄清楚如何使用plot_date更改y轴上的ylim并尝试了几个选项,包括ax.yaxis.set_ticks,plt.gca()。set_ylim([start,end])。绘制的线被切断并在y轴的刻度上延伸。我试图增加y轴刻度以显示7-09,或者至少延长它以使我的线不被切断。我在同一个数字上有3行,也许它与每个绘图命令重置自己的限制有关?非常感谢任何帮助。

fig = plt.figure()
ax = fig.add_subplot(111)

plt.plot_date(yearsTotal,dateStr,xdate=False,ydate=True,ls='-',marker='')
plt.plot_date(yearsTotal,dateStrSlope,xdate=False,ydate=True,ls='-',marker='',color='r')
plt.plot_date(YearsNoNans,AvNoNans,xdate=False,ydate=True,ls='-',marker='',color='g')

ax.yaxis.set_major_formatter(mdates.DateFormatter('%m-%d'))

plt.minorticks_on()
plt.grid(b=True,which='major',color='b')
plt.tick_params(axis='x',pad=20,labelsize=24)
plt.tick_params(axis='y',labelsize=24)

fig.autofmt_xdate()

问题从这里开始:start,end,stepsize没有效果。我也尝试了注释掉的选项。

start = datetime.date(1953,5,23)
end = datetime.date(1953,7,9)
stepsize=(end-start)/10
#ax.yaxis.set_ticks(np.arange(start,end,stepsize))
#plt.gca().set_ylim([datetime.date(1953, 5, 23), datetime.date(1953, 7, 9)])
#plt.gca().set_ylim(bottom=end)

locs, labels = plt.xticks()
plt.setp(labels, rotation=0)

ax.axis('tight')
plt.savefig(figPath+'brkDOY.png',bbox_inches='tight')
plt.show()

enter image description here

1 个答案:

答案 0 :(得分:0)

问题在于ax.axis('tight')这会覆盖y轴的重新缩放。尝试使用plt.tight_layout()。这是你最后应该有的代码

start = datetime.date(1953,5,23)
end = datetime.date(1953,7,9)
ax.set_ylim([start,end])

plt.tight_layout()
plt.savefig(figPath+'brkDOY.png',bbox_inches='tight')
plt.show()

我相信你也可以消除

locs, labels = plt.xticks()
plt.setp(labels, rotation=0)

只要你使用xdate = False。当x轴绘制为您不是的日期时,Matplotlib仅旋转x轴标签。