How to invert color of seaborn heatmap colorbar - colors

I use an heatmap to visualize a confusion matrix. I like the standard colors, but I would like to have 0s in light orange and highest values in dark purple.
I managed to do so only with another set of colors (light to dark violet), setting:
colormap = sns.cubehelix_palette(as_cmap=True)
ax = sns.heatmap(cm_prob, annot=False, fmt=".3f", xticklabels=print_categories, yticklabels=print_categories, vmin=-0.05, cmap=colormap)
But I want to keep these standard ones. This is my code and the image I get.
ax = sns.heatmap(cm_prob, annot=False, fmt=".3f", xticklabels=print_categories, yticklabels=print_categories, vmin=-0.05)

The default cmap is sns.cm.rocket. To reverse it set cmap to sns.cm.rocket_r
Using your code:
cmap = sns.cm.rocket_r
ax = sns.heatmap(cm_prob,
annot=False,
fmt=".3f",
xticklabels=print_categories,
yticklabels=print_categories,
vmin=-0.05,
cmap = cmap)

To expand on Ben's answer, you can do this with most if not any color map.
import matplotlib.pyplot as plt
import numpy as np
import seaborn as sns
X = np.random.random((4, 4))
sns.heatmap(X,cmap="Blues")
plt.show()
sns.heatmap(X,cmap="Blues_r")
plt.show()
sns.heatmap(X,cmap="YlGnBu")
plt.show()
sns.heatmap(X,cmap="YlGnBu_r")
plt.show()

only add cmap="rocket_r" to sns.heatmap
cmap="rocket": is the default palette of heatmap
add_r: to reverse the colors of palette
ax = sns.heatmap(cm_prob, annot=False, fmt=".3f", xticklabels=print_categories, yticklabels=print_categories, vmin=-0.05,cmap="rocket_r")

we can now quickly achieve reverse color just by putting _r in the end.
For example: for viridis => viridis_r
sns.heatmap(corr_matrix, annot=True, cmap='viridis_r');

Did you try to invert the colormap?
sns.cubehelix_palette(as_cmap=True, reverse=True)

Related

Seaborn, how to gradient color distplot depending on the x-axis value

I'd like to gradient-color the plot line in the Seaborn's distplot, depending on the x-axis value. For example if the value is 1, then the colour is blue, when 1.1 then it's blue and goes toward green, and so on, and so on. For example like on the plot-draft below:
The problem is, that I don't how to set colour map manually in Seaborn or how to force x-dependend coloring of the plot's curve.
Note that distplot has been deprecated. In the current seaborn version, kdeplot draws a kde curve.
You can grab the generated line with ax.get_lines(). And then create a multicolored line similar to this tutorial example.
Here is some code to demonstrate the idea (currently it would also still work with distplot):
from matplotlib import pyplot as plt
from matplotlib.collections import LineCollection
import seaborn as sns
import numpy as np
np.random.seed(1234)
data = np.random.uniform(-1, 1.1, (5, 1000)).cumsum(axis=1).ravel()
ax = sns.kdeplot(x=data)
x, y = ax.get_lines()[0].get_data()
segments = np.array([x[:-1], y[:-1], x[1:], y[1:]]).T.reshape(-1, 2, 2)
norm = plt.Normalize(x.min(), x.max())
lc = LineCollection(segments, cmap='turbo_r', norm=norm)
lc.set_array(x[:-1])
lc.set_linewidth(2)
ax.get_lines()[0].remove()
line = ax.add_collection(lc)
ax.fill_between(x, y, color='purple', alpha=0.1, hatch='xx')
ax.margins(x=0)
ax.set_ylim(ymin=0)
plt.show()

Highlight some labels on the x-axis on seaborn barplot

I am using seaborn to plot the heritability of some brain regions. I want to highlight the labels on the x-axis based on the brain regions. So for example, let's say that I have regions that are White matter and regions that are grey matter. I want to highlight the brain regions of the grey matter in red and the white matter regions in blue. How can I do that?
Here is the code that I use:
b = sns.barplot(x="names", y="h2" ,data=df, ax = ax1)
ax1.set_xticklabels(labels= df['names'].values.ravel(),rotation=90,fontsize=5)
ax1.errorbar(x=list(range (0,165)),y=df['h2'], yerr=df['std'], fmt='none', c= 'b')
plt.tight_layout()
plt.title('heritability of regions ')
plt.show()
What should I add to do what I want?
Thanks
You can add a new column to the dataframe and use that as the hue parameter. To change the color of the ticklabels, you can loop through them and use set_color depending on the grey/white column.
import seaborn as sns
import pandas as pd
import numpy as np
from matplotlib import pyplot as plt
df = pd.DataFrame({'names': list('abcdefghij'),
'h2': np.random.randint(10, 100, 10),
'grey/white': np.random.choice(['grey', 'white'], 10)})
ax1 = sns.barplot(x='names', y='h2', hue='grey/white', dodge=False, data=df)
ax1.set_xticklabels(labels=df['names'], rotation=90, fontsize=15)
# ax1.errorbar(x=list(range(0, 165)), y=df['h2'], yerr=df['std'], fmt='none', c='b')
for (greywhite, ticklbl) in zip(df['grey/white'], ax1.xaxis.get_ticklabels()):
ticklbl.set_color('red' if greywhite == 'grey' else 'blue')
plt.title('heritability of regions ')
plt.tight_layout()
plt.show()

How to center a colorbar at a specific color for Seaborn Heatmap?

Is it possible to specify the color of center of colorbar in seaborn heatmap?
As example the ceneter of colorbar of the following heat map is 70, and I want to be specified with black color instead of white.
Thanks in advance.
the example heatmap
You can use DivergingNorm to specify an off-centered normalization. To create the cmap with black in the center, use LinearSegmentedColormap
from matplotlib.colors import LinearSegmentedColormap, DivergingNorm
cmap = LinearSegmentedColormap.from_list('BkR',['blue','black','red'])
norm = DivergingNorm(vmin=0, vcenter=70, vmax=100)
x,y = np.random.randint(0,100, size=(2,50))
plt.figure()
plt.scatter(x,y,c=y, norm=norm, cmap=cmap)
plt.colorbar()
plt.show()

Change the automatic color of matplotlib to hex colors automatically python3

I created a pie chart using matplotlib and I'd like to change the default colors to more softer colors, such as the hex RGB or RGBA string colors. I have the below script so far:
colors = ['#ff9999', '#66b3ff', '#99ff99', '#ffcc99']
explode = ((0.05,)*(len(annotation_df.index)))
fig1, ax1 = plt.subplots()
ax1.pie(annotation_df['count'], labels=annotation_df['annotation'], autopct='%1.1f%%', startangle=90, pctdistance=0.85, explode=explode,colors=colors) #colors=colors,
# draw circle
centre_circle = plt.Circle((0, 0), 0.70, fc='white')
fig = plt.gcf()
fig.gca().add_artist(centre_circle)
# Equal aspect ratio ensures that pie is drawn as a circle
ax1.axis('equal')
plt.tight_layout()
plt.show()
The problem is I need the colors to be set automatically, and I don't want specifically write the colors, as written above in the script.
Anyone knows how to do it?
You may define a color cycler to contain the colors you want to use.
import matplotlib.pyplot as plt
plt.rcParams['axes.prop_cycle'] = plt.cycler('color',
['#ff9999', '#66b3ff', '#99ff99', '#ffcc99'])
fig1, ax1 = plt.subplots()
ax1.pie([1,2,3], labels=list("ABC"), autopct='%1.1f%%')
ax1.axis('equal')
plt.tight_layout()
plt.show()
If you have less wedges than colors in the cycler only the those colors needed are used. If you have more wedges than colors in the cycler, they would be repeated. You can put as many colors as you like into the color cycler.

How to achieve the Fiji "HiLo" colormap in matplotlib image plots, to mark under and overexposed pixels

Matplotlib's colormaps do not provide the HiLo colormap for images, which is often used in microscopy. HiLo shows a gray-level gradient from low to high values, but values at the low-end are shown in blue and ones at the upper end in red.
How can one get this color-map for matplotlib images?
To achieve this one can use the 'set_under' and 'set_over' methods of the LinearSegmentedColormap class, of which the colormaps are inherited.
# minimal example
from matplotlib import cm
import matplotlib.pyplot as plt
from numpy import arange
im_array = arange(0, 256)
cmap = cm.gray
cmap.set_over(color='red')
cmap.set_under(color='blue')
fig = plt.figure()
ax = fig.add_subplot(111)
vmin = im_array.min() + 1
vmax = im_array.max() - 1
ax.imshow(im_array.reshape((16, 16)), cmap=cmap, vmin=vmin, vmax=vmax)
May be this helps someone.
Cheers!
S

Resources