使用 pandas/matplotlib 或 seaborn 排序的条形图

Sorted bar charts with pandas/matplotlib or seaborn

我有一个包含 5000 个产品和 50 个特征的数据集。其中一列是 'colors' 并且列中有超过 100 种颜色。我正在尝试绘制条形图以仅显示前 10 种颜色以及每种颜色有多少产品。

top_colors = df.colors.value_counts()
top_colors[:10].plot(kind='barh')
plt.xlabel('No. of Products');

使用 Seaborn:

sns.factorplot("colors", data=df , palette="PuBu_d");

1) 有更好的方法吗?

2) 我如何用 Seaborn 复制它?

3) 我如何绘制以使最高计数位于顶部(即条形图最顶部的黑色)

如果你想使用pandas那么你可以先排序:

top_colors[:10].sort(ascending=0).plot(kind='barh')

Seaborn 已经为您的 pandas 绘图设置了样式,但您也可以使用:

sns.barplot(top_colors.index, top_colors.values)

一个简单的技巧可能是反转绘图的 y 轴,而不是乱用数据:

s = pd.Series(np.random.choice(list(string.uppercase), 1000))
counts = s.value_counts()
ax = counts.iloc[:10].plot(kind="barh")
ax.invert_yaxis()

Seaborn barplot 目前不支持水平方向的条,但如果您想控制条出现的顺序,您可以将值列表传递给 x_order 参数。但无论如何,我认为在这里使用 pandas 绘图方法更容易。