Barplot为-:'str'和'float'返回不受支持的操作数类型 [英] Barplot returns unsupported operand type(s) for -: 'str' and 'float'
本文介绍了Barplot为-:'str'和'float'返回不受支持的操作数类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我尝试使用以下代码绘制数据透视表的条形图:
I try to plot a bar plot of a pivot_table with the following code:
fig=plt.figure(figsize=(10,10))
ax1=fig.add_subplot(111)
ax1.bar(Products.index,Products["Amount"].values)
数据透视表如下:
Amount
Material
454T006S R 167 134:11 0.000000
3457T006S R IE216 167 246:1 4.500000
67T009S R 1510K304:1 36.000000
7676009S R IE216 1510K304:1 30.500000
676T012S 167 246:1 1.000000
2324T012S R 1510 111 6.000000
1516T012S R 1510 151 50.500000
1516T012S R 1510 20:1 26.500000
但是它返回:
--'str'和'float'的不受支持的操作数类型
unsupported operand type(s) for -: 'str' and 'float'
我在做什么错了?
推荐答案
问题是您的索引值为 strings
.
我认为最简单的方法是使用 pandas.DataFrame.plot.bar
:
I think simpliest is use pandas.DataFrame.plot.bar
:
Products["Amount"].plot.bar()
您可以将字符串的值映射到 range
,绘图范围并最后添加 xticks
:
You can map values of string to range
, plot range and last add xticks
:
fig=plt.figure(figsize=(10,10))
ax1=fig.add_subplot(111)
idx=Products.index.tolist()
x = range(len(idx))
plt.bar(x, Products["Amount"].values)
plt.xticks(x, idx, rotation=90)
plt.show()
类似的解决方法是重置索引
并默认绘制 index
:
Similar solution is reset index
and plot by default index
:
fig=plt.figure(figsize=(10,10))
ax1=fig.add_subplot(111)
Products = Products.reset_index()
plt.bar(Products.index, Products["Amount"].values)
plt.xticks(Products.index, Products['Material'], rotation=90)
plt.show()
这篇关于Barplot为-:'str'和'float'返回不受支持的操作数类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文