【问题标题】:Pandas/NumPy -- Plotting Dates as X axisPandas/NumPy——将日期绘制为 X 轴
【发布时间】:2018-09-08 04:07:28
【问题描述】:

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

这个错误:

 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

【问题讨论】:

  • 这样做的原因df2['Date'] = df2.Date.astype('O') ?
  • 您的数据集中的日期可能有误
  • 日期错误是什么意思?关于你的第一个问题,创建一个对象。我正在关注本教程-->matplotlib.org/gallery/recipes/common_date_problems.html 它似乎指向了我
  • 从链接中删除这两个零
  • 你能告诉我 df2.head() 吗?

标签: python pandas numpy


【解决方案1】:
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()

输出:

【讨论】:

    猜你喜欢
    • 2018-08-31
    • 1970-01-01
    • 1970-01-01
    • 2019-09-19
    • 2019-04-22
    • 2015-01-19
    • 2016-07-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多