我想绘制一个图,但熊猫会不断对索引(N)重新排序。
我希望顺序为N = 50,100,200,其中每个N都有三列,即2x2 3x3 4x4
f1 = pd.DataFrame({"User": ["2 x 2 x 2","3 x 3 x 3", "4 x 4 x 4","2 x 2 x 2","3 x 3 x 3", "4 x 4 x 4","2 x 2 x 2","3 x 3 x 3", "4 x 4 x 4"],\
"clm2": profit_comparison[0:len(profit_comparison)],\
"N": ["N=50","N=50","N=50","N=100","N=100","N=100","N=200","N=200","N=200"]})
with PdfPages('profit(n,p).pdf') as pdf:
ax1= df1.pivot(index = "N", columns = "User", values = "clm2").plot.bar(edgecolor = "white")
ax1.set_ylabel("Profit")
pdf.savefig()
plt.close()
答案 0 :(得分:0)
我猜您看到的错误顺序是100、200、50。如果是这种情况,那就是熊猫正在按字母顺序对索引进行排序。
在这种情况下,您有两个选择:第一个是根据索引的数字信息对索引进行排序,然后可以检查this question以了解其操作方式。
第二种方法是只更改数据以在50之前插入零或空格,这样行就可以了:
profit_comparison = range (9)
f1 = pd.DataFrame (
{
"User": [
"2 x 2 x 2","3 x 3 x 3", "4 x 4 x 4",
"2 x 2 x 2","3 x 3 x 3", "4 x 4 x 4",
"2 x 2 x 2","3 x 3 x 3", "4 x 4 x 4"
],
"clm2": profit_comparison[:],
"N": [
"N= 50","N= 50","N= 50",
"N=100","N=100","N=100",
"N=200","N=200","N=200"
]
},
)
ax1 = f1.pivot(
index = "N",
columns = "User",
values = "clm2"
).plot.bar(edgecolor = "white")
ax1.set_ylabel("Profit")
一些附加说明:
[:len(profit_comparison)]
;您可以只使用profit_comparison[:]
sort_index()
生成的数据帧上使用pivot