1

I have graphs with just 3 colors - Green, Red, Grey for values A, B, C. The application uses group by and value counts to get the cumulative count of A, B, and C across months and shows a donut chart, barh, and a bar chart. The colors shift from graph to graph - on one they A is green and the other graph with the same data shows A as red.

Simple fix, right?

def color_for_label(label):
    xlate = {'A': 'green',
             'B': 'red',
             'C': 'grey',
             }
    return [xlate[x] for x in label]


chart = gb.unstack(level=-1)
               .plot.barh(color=color_for_label(gb.index[0:2].names), 
                width=.50,
                stacked=True, 
                legend=None)  

The data returns an index sometimes and a multiindex other times. It chokes on and but works on

The colors are constant Red/Green/Grey that always go with the values A/B/C.

I've tried checking datatypes and try/except structures, but both got too complex quickly. Anyone got a simple solution to share?

Lets use the data from this example pandas pivot table to stacked bar chart

df.assign(count =1 ).groupby(['battle_type']).count().plot.barh(stacked=True)

and (latter preferred - I'm not loving the groupby inconsistencies)

df.pivot_table(index='battle_type', columns='attacker_outcome', aggfunc='size').plot.barh(stacked=True)

both get me

enter image description here

I have a 3rd value, "Tie" in my example of A, B, C above, but lets ignore that for the moment.

I want to make sure that win is always green, lose is red, Tie is grey.

so I have my simple function

def color_for_label(label):
    xlate = {'win': 'green',
             'lose': 'red',
             'Tie': 'grey',
             }
return xlate[label]

so I add

....plot.barh(stacked=True, color=color_for_label(**label**))

And here I'm stuck - what do I set label to so that win is always green, lose is red and tie is grey?

1

1 Answer 1

1

Got it!

First, translate colors for the new example

def color_for_label(label):
    xlate = {'win': 'green',
             'loss': 'red',
             'tie': 'grey',
             }
    return [xlate[x] for x in label]

Then break it into two lines.

# create a dataframe
gb = df.pivot_table(index='battle_type', columns='attacker_outcome', aggfunc='size')

enter image description here

# pass the dataframe column values
gb.plot.barh(stacked=True, color=color_for_label(gb.columns.values))

enter image description here

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

1 Comment

see medium.com/dunder-data/… for additional info on why I switched to pivottable

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.