How to center a colorbar at a specific color for Seaborn Heatmap? - python-3.x

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()

Related

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 change seaborn jointplot linewidth?

hexs = sns.jointplot(a,b,marker = '.', kind = "reg", height=1.476, scatter_kws={'s':2, 'linewidth':0.1},joint_kws={'line_kws':{'linewidth':'0.5'}})
I can change the scatter size and the regression line width.
but how can I change the curve width ?(the curve pointed by the black arrow)
As the name indicates, a jointplot is a combination of some other plots.
The visual aspect of the marginal subplots can be controlled via marginal_kws=.
In this case, the marginal plots are drawn using distplot. On its turn, in a distplot, the kernel density approximation is drawn with kdeplot. The parameters of this kdeplot are controlled via the kde_kws inside the marginal_kws.
from matplotlib import pyplot as plt
import seaborn as sns
tips = sns.load_dataset("tips")
g = sns.jointplot("total_bill", "tip", data=tips, marker='.', kind="reg", height=1.476,
scatter_kws={'s': 2, 'linewidth': 0.1},
joint_kws={'line_kws': {'linewidth': 0.5}},
marginal_kws={'color': 'g', 'kde_kws': {'linewidth': 0.5}})
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 invert color of seaborn heatmap colorbar

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)

better piechart color scheme

I am trying to create a pie chart, as follows:
import matplotlib.pyplot as plt
import pandas as pd
# make a square figure and axes
plt.figure(1, figsize=(10,10))
plt.axes([0.01, 0.1, 0.6, 0.6])
# plt.style.use('fivethirtyeight')
# The slices will be ordered and plotted counter-clockwise.
labels = 'foo1', 'foo2', 'foo3', 'foo4'
fracs = pd.Series([10,30, 50,10],index=labels)
fracs.plot(kind='pie', labels=None, autopct='%1.0f%%')
plt.legend(bbox_to_anchor=(0.95, .9), loc=2, borderaxespad=0.,labels=labels)
plt.title('pie chart demo which should be center aligned not left', bbox={'facecolor':'0.8', 'pad':5})
plt.show()
Which is yeilding a piechart as:
But, I am facing two problem:
1) I dont like the color scheme. I would like a color scheme more inline with (I need 12 colors)
2) Titel is centered at the pie chart only. The legend is somehow out. I am trying to get the title centered over the chart and the legend.
Can someone kindly help?
I think that is a ggplot colorscheme that you are trying to emulate.
And your plt.axes command is what is displacing your chart to the left.
Try this:
import matplotlib.pyplot as plt
plt.style.use('ggplot')
plt.figure(1, figsize=(10,10))
labels = 'foo1', 'foo2', 'foo3', 'foo4'
sizes = [10,30, 50,10]
plt.pie(sizes, labels=labels)
plt.show()

Resources