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

标签 python pandas matplotlib time

通过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/

相关文章:

python - 使用 apply 函数在 pandas 中创建一个具有舍入值的新列

python - 在 Matplotlib 中定义 GridSpec 的宽度/高度

python - 如何在 python shell 中重新加载一个类?

python - 根据其他数据帧中的值检索一行数据帧中的值

python - 为 Pandas 数据框中的每个日期时间添加多行

python - 从特定索引中重新选择 Pandas 数据框

python - 两个三次表达式之间的解析交集

python - 指向曲线上一点的箭头

python - 在 Numpy 数组子类中更改 `__getitem__` 和 `__setitem__` 的行为

python - 将类似字符串的目录树转换为嵌套列表数据结构python