[英]Add years to x-axis in Matplotlib
I have the following plot which was made using hours in the x-axis: 我有以下使用x轴小时制作的图:
I would like to change the text on the x-axis to be years rather than hours. 我想将x轴上的文本更改为数年而不是数小时。 So I need years to correspond with specific hours.
所以我需要几年才能与特定时间相对应。 I've read that this might be done using
plt.xticks(x, my_xticks)
and indexing of my x
array, but is not working for me. 我已经读过这可能是使用
plt.xticks(x, my_xticks)
和我的x
数组的索引来完成的,但对我来说不起作用。 It would be really appreciated if somebody give me some advice on how to do this. 如果有人就如何做到这一点给我一些建议,我们将非常感激。 Thank you very much.
非常感谢你。
Here is an example of my code: 这是我的代码示例:
fig_1,ax1 = plt.subplots()
x1 = np.arange(0,129392) #hourly data
x2 = np.linspace(0,129392,5390) #daily data
y_norm = 150.*np.ones([129392,1])
ax1.plot(x1,Data_OBS_h,'k',marker='o',linestyle=' ',label='PM10-1h',linewidth=1.5)
ax1.plot(x2,Data_OBS,'r',linestyle='-',label='PM10-24h',linewidth=1.5)
ax1.plot(x1,y_norm,'b',linestyle='-',label='standard',linewidth=1.5)
Change the x-axis to datetime objects, and then simply call 将x轴更改为datetime对象,然后只需调用
plt.plot(x,y)
plt.gcf().autofmt_xdate()
There are also manual (but unfortunate) ways of doing this, which I'll edit in if that does not work. 还有手动(但不幸)的方法,如果这不起作用我将编辑。
Replace x1
and x2
with this: 用这个替换
x1
和x2
:
import datetime
delta_h = datetime.timedelta(hours=1)
start = datetime.datetime(2001, 1, 1)
x1 = [start + x * delta_h for x in range(129392)]
x2 = [start + x * delta_h for x in range(0, 129392, 24)]
This is useful if you don't have an actual starting date but just a time difference starting from a time zero: 如果您没有实际的开始日期,只是从零时间开始的时差,这非常有用:
import math
days_per_year = 365.2425
hours_per_day = 24
ax1.xaxis.set_major_locator(plt.FixedLocator(
range(0, x1[-1], math.ceil(hours_per_day * days_per_year))))
ax1.xaxis.set_ticklabels(range(math.ceil(x1[-1] / (hours_per_day * days_per_year))))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.