matplotlib 我有一个只有夏季月份的日期时间框架,我如何绘制它是连续的,而不是按年分隔?

2mbi3lxu  于 6个月前  发布在  其他
关注(0)|答案(1)|浏览(46)

正如我在标题中提到的,我有一个日期时间框架,我已经编辑为只包括夏季月份。当我去绘制它时,它看起来是这样的。我如何修复它,使年份之间没有差距?Plot of current data
我不知道从哪里开始,除了从日期时间转换它,但我真的不想这样做。

kpbpu008

kpbpu0081#

  • 很难帮助你没有任何其他信息。*

假设你有如下的结构:

>>> df
      Datetime   temp
0   2021-06-21  76.66
1   2021-06-22  81.79
2   2021-06-23  68.95
3   2021-06-24  84.59
4   2021-06-25  65.41
..         ...    ...
265 2023-09-14  82.87
266 2023-09-15  70.50
267 2023-09-16  76.81
268 2023-09-17  75.20
269 2023-09-18  73.11

[270 rows x 2 columns]

>>> df.groupby(df['Datetime'].dt.year)['Datetime'].agg(['min', 'max'])
                min        max
Datetime                      
2021     2021-06-21 2021-09-18
2022     2022-06-21 2022-09-18
2023     2023-06-21 2023-09-18

字符串
如果你想要像下图这样的东西,你可以这样做:

xticks = df.loc[df['Datetime'].dt.day.eq(1), 'Datetime'].dt.strftime('%Y-%m')
vlines = df.groupby(df['Datetime'].dt.year)['Datetime'].idxmax()[:-1]
ax = df.plot(y='temp', rot=45)
ax.set_xticks(xticks.index, xticks)
ax.vlines(vlines, ymin=df['temp'].min(), ymax=df['temp'].max(), color='red', ls='dashed')
plt.tight_layout()
plt.show()


输出量:


的数据
Minimal Working Example

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt

period0 = pd.Series(pd.date_range('2021-06-21', periods=90, freq='D'))
period1 = pd.Series(pd.date_range('2022-06-21', periods=90, freq='D'))
period2 = pd.Series(pd.date_range('2023-06-21', periods=90, freq='D'))
df = pd.concat([period0, period1, period2], axis=0, ignore_index=True).to_frame('Datetime')
df['temp'] = np.round(65 + np.random.random(90*3) * 20, 2)

相关问题