Pandas: df.plot bars with different colors depending on values

Created on 23 Nov 2017  路  5Comments  路  Source: pandas-dev/pandas

I found a strange behavior with pandas.plot colors my version of pandas is

import pandas as pd
pd.__version__
'0.20.3'

Problem description

Before when i wanted to assign different colors to bars depending on value i could simply do

n=10
df = pd.DataFrame({"a":np.arange(1,n)})
df.plot(kind='bar', color=np.where(df["a"]>2, 'g', 'r'))

Now not only it accepts only a tuple instead of an array as color but it breaks whenever the tuple is longer than 5

n=5
df = pd.DataFrame({"a":np.arange(1,n)})
colors = tuple(np.where(df["a"]>2, 'g', 'r'))
df.plot(kind='bar', color= colors )
n=6
df = pd.DataFrame({"a":np.arange(1,n)})
colors = tuple(np.where(df["a"]>2, 'g', 'r'))
df.plot(kind='bar', color= colors )
Visualization

Most helpful comment

I found that you have different color for each bar when you do this
n=6
df = pd.DataFrame({"a":np.arange(1,n)})
df['a'].plot(kind='bar', color=tuple(["g", "b","r","y","k"]))

All 5 comments

@rpanai Thanks for reporting. This seems odd. The old pandas, eg. 1.9, works well.
Also this works in current pandas.

n=10
df = pd.DataFrame({"a":np.arange(1,n)})
df.plot(kind='bar', color=[np.where(df["a"]>2, 'g', 'r')])

@Licht-T Yes this work but i can't understand why the other case doesn't work.
For example try these codes:

n=5
df = pd.DataFrame({"a":np.arange(1,n)})
df.plot(kind='bar', color=tuple(["g", "b","r","y"]))

n=6
df = pd.DataFrame({"a":np.arange(1,n)})
df.plot(kind='bar', color=tuple(["g", "b","r","y","k"]))

on the first case my bars have different colors while on the second not. Then if I pass a list all the bars have the same color.

@rpanai Seems that plot method supports the only one color.
The tuple which length is 3, 4 works because _validate_color_args is wrong and the argument treated as RGB or RGBA color case.
https://github.com/pandas-dev/pandas/blob/8d04dafd48d541042613548183b62288ef7e97b3/pandas/plotting/_core.py#L198

I found that you have different color for each bar when you do this
n=6
df = pd.DataFrame({"a":np.arange(1,n)})
df['a'].plot(kind='bar', color=tuple(["g", "b","r","y","k"]))

This seems to still be an issue and @yz3101's response above solved it for me. Explicitly calling the column of the DataFrame allowed me to specify colours. Otherwise, it doesn't work.

Was this page helpful?
0 / 5 - 0 ratings