Color of bar in chart based off boolean value in the same row of dataframe

Viewed 1057

I'm Trying to construct a bar chart with the colour of the bars being influenced from the boolean value on the same row in the dataframe. In this example I'm wanting has_chocolate with False to be red and True to be green when sales are put in a bar chart.

import pandas as pd
import matplotlib.pyplot as plt
cake_sales_df

index     cake          sales          has_chocolate
0         empire        15             False
1         tea cake      25             True
2         snowball      20             True
3         hob-nob       50             True
4         lotus         3              False

What I've attempted so far with using an outside function or a condition

cake_sales_df.plot(x='cake', y='sales',
                        kind='bar', color = 'green' if cakes_sales_df['has_chocolate'] == True else 'red')

have all gotten me the same error

ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().
2 Answers

You can pivot the data:

(df.pivot(index='cake',columns='has_chocolate',values='sales')
   .plot.bar(stacked=True)
)

Output:

enter image description here

Or you can use seaborn:

import seaborn as sns

sns.barplot(data=df, x='cake', y='sales', hue='has_chocolate',
            palette={True:'g', False:'r'},
            dodge=False)

Output:

enter image description here

I was able to use matplotlib to make a bar chart. But due to the lack of reputation the picture is not embedded. Instead the links to imgur are provided.

import pandas as pd
from matplotlib.patches import Patch

columns = ['cake', 'sales', 'has_chocolate']
df = pd.DataFrame([['empire', 15, False],['tea cake',25, True],['snowball', 20, True],['hob-nob', 50, True],['lotus', 3, False]], columns = columns).set_index('cake')
df

data in jupyter

colours = {True: "#44bd32", False: "#273c75"}
df['sales'].plot(
    kind="bar", 
    color=df['has_chocolate'].replace(colours)
).legend(
    [   Patch(facecolor=colours[True]),
        Patch(facecolor=colours[False])
    ], [True, False]
)

the bar chart

Related