【问题标题】:Pandas TypeError when adding bar chart to the plot将条形图添加到绘图时出现 Pandas TypeError
【发布时间】:2020-02-12 21:32:27
【问题描述】:

我正在创建一个包含两个线图的情节 - 计划生产和实际生产,以及显示两者之间差异的条形图。

我已经创建了线图:

ax.plot_date(df['Date'], df['Planned_x'], 'b-', c='red')
ax.plot_date(df['Date'], df['Actuals'], 'b-', c='blue')

后来我在 Stack Overflow 上的一个老问题中看到,如果我将 plot_date 切换为普通 plot 并分别通过 ax.xaxis_date(),那么合并条形图会更容易是所有 plot_date 所做的,所以我已经相应地更改了代码。

只要我不尝试添加条形图,一切都可以正常工作,但只要我这样做:

ax.plot(df['Date'], df['Planned_x'], 'b-', c='red')
ax.plot(df['Date'], df['Actuals'], 'b-', c='blue')
ax.bar(df['Date'], df['Delta'], c='black', width=1)
ax.xaxis_date()

...我开始收到 TypeErrors:TypeError: the dtypes of parameters x (datetime64[ns]) and width (int32) are incompatible

我环顾四周,但我发现的大部分都是关于 matplotlib 和 Pandas github 页面的错误报告,没有对我有任何帮助的解决方案。

编辑: 这是来自 Dataframe 的示例数据:

          Date   Planned_x  Actuals     ...       C2P (%)  Planned_y       Delta
766 2019-09-19  284.000000    439.0     ...           NaN        NaN -155.000000
767 2019-09-20  284.000000    469.0     ...           NaN        NaN -185.000000
768 2019-09-21  260.000000    240.0     ...           NaN        NaN   20.000000
769 2019-09-22  305.000000    229.0     ...           NaN        NaN   76.000000
770 2019-09-23  351.000000    225.0     ...      0.533391        NaN  126.000000
771 2019-09-24  387.353430      1.0     ...           NaN        NaN  386.353430
772 2019-09-25  444.317519    152.0     ...           NaN        NaN  292.317519
773 2019-09-26  475.557830    300.0     ...           NaN        NaN  175.557830
774 2019-09-27  404.524517    150.0     ...           NaN        NaN  254.524517
775 2019-09-28  355.303705    550.0     ...           NaN        NaN -194.696295

【问题讨论】:

  • 你能告诉我们一些数据框中的数据吗?为了能够重现您的问题。谢谢
  • 很抱歉。我已经用数据示例编辑了原始帖子。
  • 你能展示一个可重现的例子吗?参见minimal reproducible example 或How to make good reproducible pandas examples,即一段可运行的代码,从中可以清楚地看出数据类型;并说明正在使用的 matplotlib 和 pandas 的版本?

标签: python pandas matplotlib typeerror


【解决方案1】:

我使用您的数据并通过标记“.set_index('Date')”为日期列编制索引

       df = pd.DataFrame(data,columns=['Date','Planned_x','Actuals','C2P','Planned_y','Delta']).set_index('Date')

我假设您已经有一些代码可以将 plt 板附加到您的数据中,例如:

       ax = plt.subplot(111)

然后你欺骗 matplotlib,说:

       plt.bar(df.index, df.Delta)

请记住,您的索引是您的数据框列日期。

我在这里看到的唯一问题是日期标签弄乱了,也许您需要选择显示减少的数据量左右。

【讨论】:

  • 谢谢!索引工作!现在我的三个地块都运行良好。我使用plt.setp(plt.xticks()[1], rotation=30, ha='right') 对角地获取日期刻度,这样它就不会那么混乱了。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-05-24
  • 1970-01-01
  • 1970-01-01
  • 2018-05-29
  • 2020-10-03
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多