【问题标题】:Sorted bar charts with pandas/matplotlib or seaborn使用 pandas/matplotlib 或 seaborn 排序的条形图
【发布时间】:2015-03-17 07:36:06
【问题描述】:

我有一个包含 5000 种产品和 50 项功能的数据集。其中一列是“颜色”,该列中有 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)我如何绘制使得最高计数位于顶部(即条形图最顶部的黑色)

【问题讨论】:

标签: python matplotlib pandas seaborn


【解决方案1】:

一个简单的技巧可能是反转你的绘图的 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 绘图方法更容易。

【讨论】:

    【解决方案2】:

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

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

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

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

    【讨论】:

    • 谢谢。为了澄清,颜色是其中的一列。因此,您的答案将绘制整个数据集,而不仅仅是颜色列。试过 df.colors[:10].sort(ascending=0).plot(kind='barh'),没用。 Seaborn 也一样。有什么想法吗?
    • 得到错误:“AttributeError: 'NoneType' 对象没有属性 'plot'”。 Seaborn 在这种情况下似乎不起作用。
    • 谢谢,我解决了。 top_colors.sort() top_colors[-10:].plot(kind='barh')
    猜你喜欢
    • 2017-10-01
    • 2014-05-03
    • 1970-01-01
    • 2018-12-17
    • 2019-02-18
    • 2023-03-11
    • 2023-03-16
    • 2021-04-21
    相关资源
    最近更新 更多