Reputation: 25
I have the following barh plot of a given dataframe:
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
df = pd.DataFrame({"first":np.arange(1,6), "second":np.arange(2,7)})
df.plot(kind="barh", color=tuple(["g", "b"]))
I want to switch to a custom color, namely "#af12be22", the bar that corresponds to df.loc[0,"a"], that is the shortest green bar.
Idealy I would like to have a simple way to control for colors of each of the cells, say by giving a dataframe as the argument of the "color" parameter of the .plot method. Something like:
df = pd.DataFrame({"first":np.arange(1,6), "second":np.arange(2,7)})
df_colors = pd.DataFrame({"first":["#af12be22"] + 4*["g"], "second":5*["b"]})
df.plot(kind="barh", color=df_color)
Is it possible ?
I looked at the pandas.DataFrame.plot documentation and saw that "color" seemed to only allow color variation from a column of a dataframe to another, but not within a column. I tried to change the df_color into an np.array or a list, but did not help either, with the following error message:
ValueError: Invalid color ['#af12be22' 'g' 'g' 'g' 'g']
I do understand the error, but would tike to know if there is an easy workaround
Upvotes: 1
Views: 102
Reputation: 9967
The below change (updated code)
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
df = pd.DataFrame({"first":np.arange(1,6), "second":np.arange(2,7)})
df.plot(kind="barh", color={"first":["#af12be22"] + 4*["g"], "second":5*["b"]})
will give you what I think you are looking for. Hope this helps.
Upvotes: 1