Change colours of Pandas bar chart

后端 未结 2 528
旧巷少年郎
旧巷少年郎 2021-01-03 05:43

I want the bars in a Pandas chart to each be given a different colour. The solution looks pretty simple according to this post and ones like it.

When I try to emulat

相关标签:
2条回答
  • 2021-01-03 05:53

    Let's use this code instead:

    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)))])
    

    0 讨论(0)
  • 2021-01-03 06:02

    This should also work:*

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

    This is different because df['Degree'] is a series.

    Pandas Series seem to be plotted with each bar a different colour (presumably as each is assumed to be from a different category or label) whereas in a dataframe each series is assumed to be a set of values from one category so they are given the same colour.

    For example:

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

    Produces:

    UPDATE:

    * Apparently for pandas versions < 0.17.0 you must use s.plot(kind='bar') not s.plot.bar(). I suspect the colour behaviour I am showing here is also version-specific. This demo was done with version 0.22.0.

    0 讨论(0)
提交回复
热议问题