【问题标题】:Change colours of Pandas bar chart更改 Pandas 条形图的颜色
【发布时间】:2018-02-08 13:48:09
【问题描述】:

我希望 Pandas 图表中的每条条都具有不同的颜色。根据this post 和类似的解决方案看起来很简单。

当我尝试模拟该解决方案时,我最终会得到所有条的颜色相同(尽管与标准条的颜色不同)。我想我做错了什么,但我看不到它是什么。还有人看吗?

fig = df.plot(kind='bar',    # Plot a bar chart
            legend=False,    # Turn the Legend off
            width=0.75,      # Set bar width as 75% of space available
            figsize=(8,5.8),  # Set size of plot in inches
            colormap='Paired')

colormap='Paired' 是用来改变颜色的位。我明白了:

很好,但是所有的条都是相同的颜色!正如您在上面看到的,我正在对绘图进行其他更改,但它们都是文本格式或轴细节的删除。

【问题讨论】:

    标签: pandas matplotlib plot


    【解决方案1】:

    让我们改用这段代码:

    df.plot(kind='bar',    # Plot a bar chart
            legend=False,    # Turn the Legend off
            width=0.75,      # Set bar width as 75% of space available
            figsize=(8,5.8),  # Set size of plot in inches
            color=[plt.cm.Paired(np.arange(len(df)))])
    

    【讨论】:

    • 成功了!有效!有效!我的天,让我挠了很久。
    • 有机会你能解释一下每一点的作用plt.cm.Paired(np.arange(len(df)))]
    • 当然。 plt 是您对 matplotlib 库的别名,cm 是颜色图,而 Paired 是您想要的颜色集。 np.arange 创建一个从 0 到数据帧 len 的范围。因此,您将从 Paired 中获得第一组颜色作为数据帧的长度。
    • @ImportanceOfBeingErnest 你能看看这个吗?我开始认为 colormap='Paired' 不起作用是一个错误。
    【解决方案2】:

    这也应该有效:*

    df['Degree'].plot.bar()
    

    这是不同的,因为df['Degree'] 是一个系列。

    Pandas Series 似乎是用不同颜色绘制的每个条形图(大概是因为每个条形图都被假定来自不同的类别或标签),而在数据框中,每个系列被假定为来自一个类别的一组值,因此它们是赋予相同的颜色。

    例如:

    s = pd.Series({'a': 100, 'b': 74, 'c': 50})
    s.plot.bar()
    

    生产:

    更新:

    * 显然对于 s.plot(kind='bar') 而不是 s.plot.bar()。我怀疑我在这里展示的颜色行为也是特定于版本的。此演示使用 0.22.0 版本完成。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-08-03
      • 2012-01-19
      • 1970-01-01
      • 1970-01-01
      • 2012-10-18
      • 2013-12-11
      • 1970-01-01
      相关资源
      最近更新 更多