我在绘制使用pandas date_range
和period_range
创建的时间序列数据时遇到问题。前者行得通,但后者不行。要说明该问题,请考虑以下内容
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
# random numbers
N = 100
z = np.random.randn(N)
ts = pd.DataFrame({'Y': z, 'X': np.cumsum(z)})
# 'date_range' is used
month_date = pd.date_range('1978-02', periods=N, freq='M')
df_date = ts.set_index(month_date)
# 'period_range' is used
month_period = pd.period_range('1978-02', periods=N, freq='M')
df_period = ts.set_index(month_period)
# plot
plt.plot(df_date);plt.show()
plt.plot(df_period);plt.show()
plt.plot(df_date)
给出了一个很好的数字,而plt.plot(df_period)
生成了以下错误,这是我不理解的:
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<Figure size 432x288 with 1 Axes>
这是一个预期的结果吗?这里我漏掉了什么?
BTW、df_date.plot()
和df_period.plot()
都工作得很好,不会造成任何问题。
提前谢谢。
发布于 2018-07-13 07:11:38
两个dateframes的索引类型不同:
print(type(df_date)) # pandas.core.indexes.datetimes.DatetimeIndex
print(type(df_period)) # pandas.core.indexes.period.PeriodIndex
Matplotlib不知道如何绘制PeriodIndex
。
你可以用convert the PeriodIndex
to a DatetimeIndex
和plot来代替它
plt.plot(df_period.to_timestamp())
https://stackoverflow.com/questions/51315526
复制相似问题