【发布时间】:2018-08-01 07:24:09
【问题描述】:
我有以下数据框
Class Age Percentage
0 2004 3 43.491170
1 2004 2 29.616607
2 2004 4 13.838925
3 2004 6 10.049712
4 2004 5 2.637445
5 2004 1 0.366142
6 2005 2 51.267369
7 2005 3 19.589268
8 2005 6 13.730432
9 2005 4 11.155305
10 2005 5 3.343524
11 2005 1 0.913590
12 2005 9 0.000511
我想使用 seaborn 制作条形图,其中 y 轴是“百分比”,x 轴是“类”,并使用“年龄”列标记它们。我还想按降序排列条形图,即从大到小条形图。
为了做到这一点,我想到了以下几点:我将根据“百分比”变量的顺序更改hue_order 参数。例如,如果我按降序对Class == 2004 的“百分比”列进行排序,则为hue_order = [3, 2, 4, 6, 5, 1]。
这是我的代码:
import matplotlib.pyplot as plt
import seaborn as sns
def hue_order():
for cls in dataset.Class.unique():
temp_df = dataset[dataset['Class'] == cls]
order = temp_df.sort_values('Percentage', ascending = False)['Age']
return order
sns.barplot(x="Class", y="Percentage", hue = 'Age',
hue_order= hue_order(),
data=dataset)
plt.show()
但是,只有Class == 2005 的条形按降序排列。有什么帮助吗?
在我的问题中,我使用的是 hue 参数,因此,它不是建议的重复项。
【问题讨论】:
-
@DavidG 我也在使用 hue 参数。只是说。
-
@DavidG 你真的读过我的问题还是只是用谷歌搜索类似的东西?
-
在
hue_order中,您正在循环每个类,但您在每个循环中覆盖order,最后在最后返回order。所以你只会得到order最终的Class -
@KPLauritzen 这很明显。你能给我一个解决方案吗?
标签: python pandas matplotlib bar-chart seaborn