Pandas图:如何更改数据时间格式的xlim?

2024-04-26 22:52:16 发布

您现在位置:Python中文网/ 问答频道 /正文

日期范围为2020-01-30至2020-03-31。日期的格式为datetime64[ns]。 我想将xlim范围更改为(2020-01-30、2020-03-31),但不起作用

我的代码如下:

#Plot left Y
fig, ax1 = plt.subplots()
fig.autofmt_xdate()

x_lim = (datetime.date(2020, 1, 30), datetime.date(2020, 3, 31))

df.plot(x = 'Date', y = ["TotalCount", "CumVirusCount"], ax = ax1, xlim = x_lim)


Plot right (Y)
ax2 = ax1.twinx()
df.plot(x = 'Date', y = ["Percent"], ax = ax2, xlim = x_lim, ylim=(0,70), color = 'tab:green')

#Decorations
#ax1:
ax1.set_xlabel('Date', fontsize=18)
ax2.set_ylabel("Percentage")

plt.show()

情节如下:

Plot

我预计x轴上的第一个日期为2020-01-30,最后一个日期为2020-03-31

如何做到这一点?为什么我的方法不起作用? 谢谢大家!


Tags: dfdatetimedateplot格式figpltax
1条回答
网友
1楼 · 发布于 2024-04-26 22:52:16

您确实可以在代码中使用xlim=...设置x范围,而且效果很好。但是matplotlib默认情况下放置在x轴上的记号不一定包括最小值和最大值。要改变这一点,您必须改变刻度,而不是范围。Pandas的df.plot()包装器为此接受一个xticks关键字参数,例如,在plot函数调用中传递:

xticks=[x_lim[0], <some in-between dates to label>, x_lim[1]] 

相关问题 更多 >