简体   繁体   English

如何修复我的 Python Plot 上的日期时间 x 轴?

[英]How do I fix the datetime x-axis on my Python Plot?

I'm trying to plot a graph of time x precipitation, however, the values on the x-axis don't match the values on the y-axis.我正在尝试 plot 时间 x 降水图,但是,x 轴上的值与 y 轴上的值不匹配。 The plot itself it's correct, but the x-axis is not. plot 本身是正确的,但 x 轴不是。 The context is that I created a Prophet model to predict monthly precipitation, after generating the values, I plotted the test against the prediction, and while the lines seem correct, the dates look shifted one 'unit' to the left:上下文是我创建了一个 Prophet model 来预测月降水量,在生成值之后,我根据预测绘制了测试图,虽然线条看起来是正确的,但日期看起来向左移动了一个“单位”:

Precipitation x Month:降水量 x 月:

图片

Test Values:测试值:

    Date    Precipitation
443 2020-12-31  273.2
444 2021-01-31  215.5
445 2021-02-28  180.6
446 2021-03-31  138.4
447 2021-04-30  54.4
448 2021-05-31  44.4
449 2021-06-30  16.2
450 2021-07-31  39.4
451 2021-08-31  44.4
452 2021-09-30  39.5
453 2021-10-31  91.9
454 2021-11-30  98.6
455 2021-12-31  127.3
456 2022-01-31  308.5

Prediction Values:预测值:

    Date    Precipitation
443 2020-12-31  133.7
444 2021-01-31  272.0
445 2021-02-28  222.0
446 2021-03-31  177.3
447 2021-04-30  75.9
448 2021-05-31  81.5
449 2021-06-30  31.9
450 2021-07-31  41.7
451 2021-08-31  28.9
452 2021-09-30  42.9
453 2021-10-31  111.4
454 2021-11-30  129.5
455 2021-12-31  126.2
456 2022-01-31  299.1

We can observe that the first value should be for 2020-12 but that's not the case.我们可以观察到第一个值应该是 2020-12,但事实并非如此。

fig = plt.figure(figsize=(12, 8))

plt.plot(test.Date, test.Precipitation, 's-r')
plt.plot(previsao.Date, previsao.Precipitation, 's-b')

plt.title('Precipitação por Mês na Cidade de São Paulo em $mm$', fontsize=20)

plt.ylabel('Precipitação ($mm$)', fontsize=12)
plt.xlabel('Ano')
plt.legend(['Real', 'Previsão']);
plt.show() 

Can anyone point out what I'm doing wrong here?谁能指出我在这里做错了什么? I believe I'm doing something wrong when plotting the graph but I cannot figure it out.我相信我在绘制图表时做错了什么,但我无法弄清楚。

There are a couple of things you will need to do.您需要做几件事。 Firstly make sure that the date columns are in datetime format.首先确保日期列是日期时间格式。 You can check this using test.info() and previsao.info() and see that the dtype is datetime.您可以使用test.info()previsao.info()进行检查,并查看数据类型是否为日期时间。 If not, use pd.to_datetime() .如果没有,请使用pd.to_datetime() The default format for dates displayed is the first day of the month.显示日期的默认格式是该月的第一天。 So, the dates you see will appear like it is shift by a month.因此,您看到的日期看起来像是偏移了一个月。 But, as you have dates which are the last date of the month, you will need to change display to show the last date using bymonthday=-1 in the MonthLocator .但是,由于您的日期是该月的最后一天,因此您需要使用 MonthLocator 中的MonthLocator bymonthday=-1更改显示以显示最后日期。 Finally, I have used "YYYY-MM-DD" format for display so that you can see the full date and rotated the tick labels.最后,我使用“YYYY-MM-DD”格式进行显示,以便您可以看到完整的日期并旋转刻度标签。 You can edit it to suit your needs.您可以对其进行编辑以满足您的需要。 The updated code is shown below.更新后的代码如下所示。 Hope this is what you are looking for.希望这就是您要找的。

fig = plt.figure(figsize=(12, 8))

## Use these if your dates are NOT already in datetime format
test['Date']=pd.to_datetime(test['Date'])
previsao['Date']=pd.to_datetime(previsao['Date'])

plt.plot(test.Date, test.Precipitation, 's-r')
plt.plot(previsao.Date, previsao.Precipitation, 's-b')

plt.title('Precipitação por Mês na Cidade de São Paulo em $mm$', fontsize=20)

plt.ylabel('Precipitação ($mm$)', fontsize=12)
plt.xlabel('Ano')
plt.legend(['Real', 'Previsão']);

## Added code here
import matplotlib.dates as mdates ## Import required library
months = mdates.MonthLocator(interval=1, bymonthday=-1)  ## 1 month apart & show last date
plt.gca().xaxis.set_major_locator(months) ## Set months as major locator
plt.gca().xaxis.set_major_formatter(mdates.DateFormatter('%Y-%m-%d')) ##Display format - update here to change
plt.xticks(rotation=45, ha='right') ##Adjust angle and horizontal align right
plt.show()

在此处输入图像描述

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM