首页 > 解决方案 > Pandas/NumPy——将日期绘制为 X 轴

问题描述

我的目标只是将这个简单的数据绘制成图表,x 数据是日期(日期显示在 x 轴上),价格作为 y 轴。了解字段 date 的 NumPy 记录数组的 dtype 是 datetime64[D] 这意味着它是 64 位 np.datetime64 以“天”为单位。虽然这种格式更便携,但 Matplotlib 还不能原生地绘制这种格式。我们可以通过将日期更改为 DateTime.date 实例来绘制此数据,这可以通过转换为对象数组来实现:我在下面查看 astype('0')。但我仍然得到

这个错误:

 view limit minimum -36838.00750000001 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

代码:

import pandas as pd
import matplotlib.pyplot as plt


df = pd.read_csv(r'avocado.csv')

df2 = df[['Date','AveragePrice','region']]
df2 = (df2.loc[df2['region'] == 'Albany'])

df2['Date'] = pd.to_datetime(df2['Date'])
df2['Date'] = df2.Date.astype('O')

plt.style.use('ggplot')
ax = df2[['Date','AveragePrice']].plot(kind='line', title ="Price Change",figsize=(15,10),legend=True, fontsize=12)
ax.set_xlabel("Period",fontsize=12)
ax.set_ylabel("Price",fontsize=12)

plt.show()

df.head(3)

    Unnamed: 0  Date    AveragePrice    Total Volume    4046    4225    4770    Total Bags  Small Bags  Large Bags  XLarge Bags type    year    region
0   0   2015-12-27  1.33    64236.62    1036.74 54454.85    48.16   8696.87 8603.62 93.25   0.0 conventional    2015    Albany
1   1   2015-12-20  1.35    54876.98    674.28  44638.81    58.33   9505.56 9408.07 97.49   0.0 conventional    2015    Albany
2   2   2015-12-13  0.93    118220.22   794.70  109149.67   130.50  8145.35 8042.21 103.14  0.0 conventional    2015    Albany

标签: pythonpandasnumpy

解决方案


df2 = df[['Date', 'AveragePrice', 'region']]
df2 = (df2.loc[df2['region'] == 'Albany'])
df2['Date'] = pd.to_datetime(df2['Date'])
df2 = df2[['Date', 'AveragePrice']]
df2 = df2.sort_values(['Date'])
df2 = df2.set_index('Date')

print(df2)

ax = df2.plot(kind='line', title="Price Change")
ax.set_xlabel("Period", fontsize=12)
ax.set_ylabel("Price", fontsize=12)

plt.show()

输出:

在此处输入图像描述


推荐阅读