Change bar colors in pandas matplotlib bar chart by passing a list/tuple

Viewed 1292

There are several threads on this topic, but none of them seem to directly address my question. I would like to plot a bar chart from a pandas dataframe with a custom color scheme that does not rely on a map, e.g. use an arbitrary list of colors. It looks like I can pass a concatenated string with color shorthand names (first example below). When I use the suggestion here, the first color is repeated (see second example below). There is a comment in that post which eludes to the same behavior I am observing. Of course, I could do this by setting the subplot, but I'm lazy and want to do it in one line. So, I'd like to use the final example where I pass in a list of hex codes and it works as expected. I'm using pandas versions >=0.24 and matplotlib versions >1.5. My questions are:

  • Why does this happen?
  • What am I doing wrong?
  • Can I pass a list of colors?

pd.DataFrame( [ 1, 2, 3, 4, 5 ] ).plot( kind="bar", color="brgmk" )

enter image description here

pd.DataFrame( [ 1, 2, 3, 4, 5 ] ).plot( kind="bar", color=[ "b", "r", "g", "m", "k" ] )

enter image description here

pd.DataFrame( [ 1, 2, 3, 4, 5 ] ).plot( kind="bar", color=[ "#0000FF", "#FF0000", "#008000", "#FF00FF", "#000000" ] )

enter image description here

1 Answers

When plotting a dataframe, the first color information is used for the first column, the second for the second column etc. Color information may be just one value that is then used for all rows of this column, or multiple values that are used one-by-one for each row of the column (repeated from the beginning if more rows than colors). See the following example:

pd.DataFrame( [[ 1, 4], [2, 5], [3, 6]] ).plot(kind="bar", color=[[ "b", "r", "g" ], "m"] )

enter image description here

So in your case you just need to put the list of color values in a list (specifically not a tuple):

pd.DataFrame( [ 1, 2, 3, 4, 5 ] ).plot( kind="bar", color=[[ "b", "r", "g", "m", "k" ]] )

or

pd.DataFrame( [ 1, 2, 3, 4, 5 ] ).plot( kind="bar", color=[[ "#0000FF", "#FF0000", "#008000", "#FF00FF", "#000000" ]] )

The first case in the OP (color="brgmk") works as expected as pandas internally puts the color string in a list (strings are not considered list-like).

Related