Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Seaborn conditional colors based on value

Tags:

python

seaborn

I have a Seaborn plot (in this case a box plot, here is a simplified version

sns.boxplot(x="Question", y="Score", hue="Item", data=scores[scores['Item']=='34x'], palette="PRGn")

The data looking like this...

    Item    Question    Score   Section    Event    Evaluator
    34x       Mar1        4     Maritime    Boat    6
    34x       Mar2        3     Maritime    Boat    6
    34x       Multi1      3     Multinet    Boat    6
    34x       Multi2      3     Multinet    Boat    6
    34x       Noise1      4     Noise       Boat    6

The plot renders fine, but I would like to color the box plots per question, based on their mean score. (i.e. anything below 1 is red, +1-2.5 yellow, +2.5 green). I tried a couple things with no good result. Any help in accomplishing this would be appreciated.

like image 867
Thatch Avatar asked Feb 02 '16 01:02

Thatch


1 Answers

You can use a customized dictionary of colors as boxplot palette parameter, it can be a name, an ordered list, or a dictionary.

I generated a Dataframe similar to yours

   Item Question     Score
0     A     Mar1  2.935605
1     A     Mar1  2.754065
2     A     Mar1  3.339259
3     A     Mar1  1.229478
4     A     Mar1  3.248582
5     A     Mar2  0.409028
6     A     Mar2  1.779707

From the df is possible to generate a customized colors palette:

custom_palette = {}
for q in set(scores.Question):
    avr = (np.average(scores[scores.Question == q].Score))
    if avr < 1:
        custom_palette[q] = 'r'
    elif avr < 2.5:
        custom_palette[q] = 'y'
    else:
        custom_palette[q] = 'g'

And use it to color your boxplot:

sns.boxplot(x="Question", y="Score", data=scores, palette=custom_palette,showmeans=True)

enter image description here

like image 178
MBe Avatar answered Sep 22 '22 05:09

MBe