[英]Pandas TypeError when adding bar chart to the plot
I am working on creating a plot featuring two line plots - planned and actual production, and a bar chart showing the difference between those.我正在创建一个 plot 具有两个线图 - 计划和实际生产,以及显示它们之间差异的条形图。
I've created line plots:我创建了线图:
ax.plot_date(df['Date'], df['Planned_x'], 'b-', c='red')
ax.plot_date(df['Date'], df['Actuals'], 'b-', c='blue')
Then later I saw in an old question on Stack Overflow that incorporating bar chart will be easier if I switched plot_date for normal plot and passed ax.xaxis_date()
separately since this is all plot_date does and so I've changed the code accordingly.后来我在 Stack Overflow 上的一个老问题中看到,如果我将plot_date切换为普通plot并单独传递
ax.xaxis_date()
,那么合并条形图会更容易,因为这就是plot_date所做的,所以我已经相应地更改了代码。
It all works fine so long as I don't try to add the bar chart, but as soon as I do it like so:只要我不尝试添加条形图,一切都可以正常工作,但只要我这样做:
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()
...I start getting TypeErrors: TypeError: the dtypes of parameters x (datetime64[ns]) and width (int32) are incompatible
...我开始收到 TypeErrors:
TypeError: the dtypes of parameters x (datetime64[ns]) and width (int32) are incompatible
I looked around, but most of all I found were bug reports on matplotlib and Pandas github pages and there were no solutions that were of any help to me.我环顾四周,但我发现的大部分都是关于 matplotlib 和 Pandas github 页面的错误报告,并且没有对我有任何帮助的解决方案。
EDIT: Here's the example data from the Dataframe:编辑:这是来自 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
I used your data and indexed the date column, by tagging ".set_index('Date')"我使用了您的数据并通过标记“.set_index('Date')”为日期列建立了索引
df = pd.DataFrame(data,columns=['Date','Planned_x','Actuals','C2P','Planned_y','Delta']).set_index('Date')
I assume you already have some code to attach the plt board to your data, like:我假设您已经有一些代码可以将 plt 板附加到您的数据中,例如:
ax = plt.subplot(111)
Then you trick the matplotlib, saying:然后你欺骗 matplotlib,说:
plt.bar(df.index, df.Delta)
Remember that your index is your dataframe column Date.请记住,您的索引是您的 dataframe 列日期。
The only problem I see here is the messed up with the date labels, maybe you need to choose to show a reduced amount of data or so.我在这里看到的唯一问题是日期标签搞砸了,也许您需要选择显示减少的数据量左右。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.