Colorbar for barplot when bar colors are selected by ranks

1.9k Views Asked by At

I am trying to produce barplot where colors of bars will be chosen according to given values from predefined set of colors. The "pahse" value determines the color. It is splitted into 3 ranges and ranges are ranked. Rank is used to call a colorfrom palette. This part works fine. But I stuck with colorbar. Colorbar should contain colors based on keys of the dictionary "rank_classes" and tiks/labels based on values what were used for ranking. I tried matplotlib's mpl.colorbar.ColorbarBase(), but it does not seem to like seaborns sns.cubehelix_palette(). I wonder how to put these two things to work together or there more straightforward solutions?

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
sns.set_style("white")
#%matplotlib inline

index = ['25', '26', '27']
count = [10, 50, 22]
phase = [0.9, 2.2, 1.2]
ranks = [0, 2, 1]

rank_classes = {0:"Ph<1", 1:"1<Ph<1.2", 2:"Ph>=1.2"}

d = {'count' : pd.Series(count, index=index),
     'phase' : pd.Series(phase, index=index),
     'rank'  : pd.Series(ranks, index=index)
    }

df = pd.DataFrame(d)

# barplot 
fig, ax = plt.subplots()
pal = sns.cubehelix_palette(3) 

x = df.index
y = list(df['count'])
z = list(df['rank'])

sns.barplot(x=x, y=y, palette=np.array(pal)[z])
sns.despine()
1

There are 1 best solutions below

1
tonu On

Almost there

import numpy as np
import matplotlib as mpl
import matplotlib.pyplot as plt
import seaborn as sns
sns.set_style("white")
%matplotlib inline

index = ['25', '26', '27']
count = [10, 50, 22]
phase = [0.9, 2.2, 1.2]
rank  = [0, 2, 1]
# 
rank_classes = {0:"Ph<1", 1:"1<Ph<1.2", 2:"Ph>=1.2"}

pal = sns.cubehelix_palette(len(index)) 
cmp = mpl.colors.LinearSegmentedColormap.from_list('my_list', pal,\
                                                    N=len(index))
plot = plt.scatter(index, count, c=range(len(index)), cmap=cmp)
plt.clf()
plt.colorbar(plot)
sns.barplot(x=index, y=count, palette=np.array(pal)[rank])
sns.despine()

Produces nice plot with colorbar. Only thing I have to figure out is how to replace colorbar's number labels (0, 0.3 ...3.0) with strings listed in the dictionary rank_classes.

Bar plot with colobar