gpt4 book ai didi

python - 当时间数据已作为索引确定时,如何绘制时间相关数据?

转载 作者:行者123 更新时间:2023-12-01 01:10:38 24 4
gpt4 key购买 nike

通过dft = dft.set_index('c_time')将时间数据设置为索引之后,我通过dftm = dft.resample('M')按月对数据进行重新采样。 sum().to_period('M') 数据如下所示

print(dftm['topic0'].head())
c_time
2012-03 0.0
2012-04 1.0
2012-05 0.0
2012-06 0.0
2012-07 0.0
Freq: M, Name: topic0, dtype: float64

如何将重采样的时间数据(bu月)设置为x轴?我没能做到这一点:

x = dftq.index
y1 = dftq['topic0']
# Plot Line1 (Left Y Axis)
fig, ax1 = plt.subplots(1,1,figsize=(16,9), dpi= 80)
ax1.plot(x, y1, color='tab:red')




ValueError: view limit minimum 0.0 is less than 1 and is an invalid Matplotlib date value. This often happens if you pass a non-datetime value to an axis that has datetime units

最佳答案

我认为这应该是 matplotlib 的 date2num 函数的情况之一:

from matplotlib.dates import date2num
x = date2num(dftq.index)

但是,你有没有尝试过

dftq.topic0.plot()

<小时/>

编辑: (问题:如何通过选择给定的时间范围进行绘图?)

您可以通过已经使用 .loc 索引要绘制的数据来做到这一点

dftm.loc['2012-04':'2012-06'].plot()

# or

dftm.topic0.loc['2012-04':'2012-06'].plot()

或者随后调整整个图的轴限制:

ax = dftm.plot()
ax.set_xlim('2012-04', '2012-06')

# or

import matplotlib.pyplot as plt
dftm.plot()
plt.xlim('2012-04', '2012-06')
<小时/>

补充: (关于使用 matplotlib api 和 date2num 进行绘图)

如果时间索引没有从 datetime 类型更改为 period 类型,则通过 matplotlib 及其 date2num 的第一个提案也可以工作。
但仍然:要在 x 轴刻度处没有整数,但格式良好的日期,您必须添加类似的东西

from matplotlib.dates import DateFormatter
xfmt = DateFormatter('%Y-%m')
ax1.xaxis.set_major_formatter(xfmt)

关于python - 当时间数据已作为索引确定时,如何绘制时间相关数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54896997/

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