gpt4 book ai didi

python - 设置时间序列的xlim

转载 作者:行者123 更新时间:2023-12-01 08:57:36 27 4
gpt4 key购买 nike

我想在 matplotlib 中画一个图,显示 2016 年和 2017 年 8 月的温度。x 轴是时间,y 轴是温度。我尝试通过共享范围从 2016-08-01 00:00:00 到 2016-08-31 23:00:00 的 x 轴,将 2 个图(一个用于 2016 年,一个用于 2017 年)堆叠在一起并仅显示该月的某一天。

import matplotlib.dates as mdates
myFmt = mdates.DateFormatter('%d')

# times series from 2016-08-01 00:00:00 to 2016-08-31 23:00:00
x = stats_august_2016.MESS_DATUM
# temperature in 08.2016
y1 = stats_august_2016.TT_TU
# temperature in 08.2017
y2 = stats_august_2017.TT_TU

f, ax = plt.subplots()

# plot temp in 08.2016
ax.plot(x, y1, 'yellow', label = '2016')
# plot temp in 08.2017
ax.plot(x, y2, 'red', label = '2017')
# format x-axis to show only days of the month
ax.xaxis.set_major_formatter(myFmt)
ax.grid(True)

plt.rcParams["figure.figsize"] = (12, 8)
plt.xlabel("Day of the Month", fontsize = 20, color = 'Blue')
plt.xticks(fontsize = 15)
plt.ylabel("Temperature ($\degree$C)", fontsize = 20, color = 'Blue')
plt.yticks(fontsize = 15)
ax.set_ylim(5, 35)
plt.title("Temperature in August 2016 and 2017", fontsize = 30, color = 'DarkBlue')
plt.legend(prop = {'size': 20}, frameon = True, fancybox = True, shadow = True, framealpha = 1, bbox_to_anchor=(1.22, 1))
plt.show()

一切看起来都很好,除了 x 轴的最后一个刻度不知何故是 2016-09-01 00:00:00。结果看起来很奇怪,最后是 1。

enter image description here

我该如何解决这个问题?

最佳答案

问题是,您的数据一直到每年 8 月 31 日晚的某个时间

# times series from 2016-08-01 00:00:00 to 2016-08-31 23:00:00

然后,Matplotlib 会自动缩放轴,直至下个月的第一天,并以您选择的格式显示为 1。如果您想避免这种情况,可以将轴的 x 限制设置为数据的最后一个时间戳

ax.set_xlim([x[0], x[-1]])

不过,轴左侧和右侧的空白边距将会消失。如果您想保留此边距,但仍想避免 9 月 1 日的刻度标签,则可以隐藏最后一个 x 刻度标签

xticks = ax.xaxis.get_major_ticks()
xticks[-1].label1.set_visible(False)

关于python - 设置时间序列的xlim,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52693490/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com