【问题标题】:Matplotlib bar plot with pandas Timestamp带有熊猫时间戳的 Matplotlib 条形图
【发布时间】:2017-04-01 07:47:10
【问题描述】:

我无法使这个非常简单的示例工作:

from numpy import datetime64
from pandas import Series
import matplotlib.pyplot as plt
import datetime

x = Series ([datetime64("2016-01-01"),datetime64("2016-02-01")]).astype(datetime)
y = Series ([0.1 , 0.2])

ax = plt.subplot(111)
ax.bar(x, y, width=10)
ax.xaxis_date()

plt.show()

我得到的错误是:

TypeError: float() argument must be a string or a number, not 'Timestamp'

注意astype(datetime) 部分——这是我在reading this other SO post 之后尝试的。没有那块,我会得到同样的错误。

另一方面,该示例与普通的 datetime64 类型一起工作得很好——也就是说,改变这两行:

x = [datetime64("2016-01-01"),datetime64("2016-02-01")]
y = [0.1 , 0.2]

所以问题一定是pandas将datetime64对象转换成的Timestamp类型。有没有办法直接使用Timestamp,而不是恢复到datetime64?我在这里使用Series/Timestamp,因为我的真正目标是从DataFrame 绘制系列。 (注意:我不能使用 DataFrame 绘图方法,因为我的真实示例在 seaborn FacetGrid 内部,我必须直接使用 matplotlib。)

【问题讨论】:

    标签: python pandas numpy matplotlib


    【解决方案1】:

    用途:

    ax.bar(x.values, y, width=10)
    

    当使用 Series 对象时。问题是您没有发送类似于数组的对象,它是 matplotlib 不知道如何处理的索引数组。 values 只返回数组

    【讨论】:

      【解决方案2】:

      由于您的目标是从 DataFrame 中绘制系列,也许您可​​以使用 pd.DataFrame.plot

      from numpy import datetime64
      from pandas import Series
      import matplotlib.pyplot as plt
      import datetime
      %matplotlib inline
      
      x = Series ([datetime64("2016-01-01"),datetime64("2016-02-01")])
      y = Series ([0.1 , 0.2])
      
      df = pd.DataFrame({'x': x, 'y': y})
      df.plot.bar(x='x', y='y')
      

      【讨论】:

      • 我希望!不幸的是,在我真正的问题中,我在 seaborn FacetGrid 内工作,需要直接使用 matplotlib