How to use NaN values as a hue with a defined color in seaborn barplot

Viewed 487

Assuming I have a DataFrame (df) similar to the one in the image below, with missing values in Score column:

enter image description here

I would like to plot a horizontal seaborn barplot, with Pvalue on the x-axis and colors of the bars corresponding to Score. Even if I define a colormap and tell it to display NaNs as black bars, they are not shown at all.

import seaborn as sns
from matplotlib import cm

bwrNan = copy(cm.get_cmap('bwr'))
bwrNan.set_bad('black')
cm.register_cmap("mycmap", bwrNan)
sns.barplot(data=df, x='Pvalue', y='Labels', hue='Score', palette='mycmap', linewidth=2, edgecolor='k', dodge=False)

enter image description here

On the other hand, if I try to use the same data in a seaborn heatmap I get the correct colors:

sns.heatmap(data=df[['Score']], cmap='mycmap')

enter image description here

1 Answers

How about a quick for loop:

for i,r in df.iterrows():
    color = 'k' if np.isnan(r['Score']) else bwrNan(r['Score'])
    plt.barh(r['Labels'],r['Pvalue'], color=color, edgecolor='k', alpha=0.6)

Output:

enter image description here

Related