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 )
Comment From: Licht-T
@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')])
Comment From: rpanai
@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.
Comment From: Licht-T
@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
Comment From: yz3101
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"]))
Comment From: rjp23
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.
Comment From: n-sweep
Still an issue in 1.5.3