1

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

image of df plot

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

1 Answer 1

1

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.

enter image description here

Sign up to request clarification or add additional context in comments.

3 Comments

Great, many thanks! Exactly what I want
@VictorDaniel Please click the check mark below the voting error. This is how you give credit to the author of the answer. And it also shows, that the problem is solved. This can save other people some time.
Yep yep, didn't know this feature existed

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.