Python Seaborn Facetgrid change xlabels - python

I just can't figure out how to change the xlabels in a Seaborn Facetgrid. It offers a method for changing the x labels with set_xlabels() but unfortunately not individually for each subplot.
I have two subplots which share the y-axis but have a different x-axes and i want to label them with different texts.
Can anybody give me a hint. Thank you in advance.

You can access the individual axes of the FacetGrid using the axes property, and then use set_xlabel() on each of them. For example:
import seaborn as sns
import matplotlib.pyplot as plt
sns.set(style="ticks", color_codes=True)
tips = sns.load_dataset("tips")
g = sns.FacetGrid(tips, col="time", hue="smoker")
g = g.map(plt.scatter, "total_bill", "tip", edgecolor="w")
g.axes[0,0].set_xlabel('axes label 1')
g.axes[0,1].set_xlabel('axes label 2')
plt.show()
Note in this example, g.axes has a shape of (1,2) (one row, two columns).

for all axis to set them once use this
g.set_axis_labels("Total bill ($)")

Related

Seaborn FacetGrid maximize size [duplicate]

How do I change the size of my image so it's suitable for printing?
For example, I'd like to use to A4 paper, whose dimensions are 11.7 inches by 8.27 inches in landscape orientation.
You can also set figure size by passing dictionary to rc parameter with key 'figure.figsize' in seaborn set method:
import seaborn as sns
sns.set(rc={'figure.figsize':(11.7,8.27)})
Other alternative may be to use figure.figsize of rcParams to set figure size as below:
from matplotlib import rcParams
# figure size in inches
rcParams['figure.figsize'] = 11.7,8.27
More details can be found in matplotlib documentation
You need to create the matplotlib Figure and Axes objects ahead of time, specifying how big the figure is:
from matplotlib import pyplot
import seaborn
import mylib
a4_dims = (11.7, 8.27)
df = mylib.load_data()
fig, ax = pyplot.subplots(figsize=a4_dims)
seaborn.violinplot(ax=ax, data=df, **violin_options)
Note that if you are trying to pass to a "figure level" method in seaborn (for example lmplot, catplot / factorplot, jointplot) you can and should specify this within the arguments using height and aspect.
sns.catplot(data=df, x='xvar', y='yvar',
hue='hue_bar', height=8.27, aspect=11.7/8.27)
See https://github.com/mwaskom/seaborn/issues/488 and Plotting with seaborn using the matplotlib object-oriented interface for more details on the fact that figure level methods do not obey axes specifications.
first import matplotlib and use it to set the size of the figure
from matplotlib import pyplot as plt
import seaborn as sns
plt.figure(figsize=(15,8))
ax = sns.barplot(x="Word", y="Frequency", data=boxdata)
You can set the context to be poster or manually set fig_size.
import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt
np.random.seed(0)
n, p = 40, 8
d = np.random.normal(0, 2, (n, p))
d += np.log(np.arange(1, p + 1)) * -5 + 10
# plot
sns.set_style('ticks')
fig, ax = plt.subplots()
# the size of A4 paper
fig.set_size_inches(11.7, 8.27)
sns.violinplot(data=d, inner="points", ax=ax)
sns.despine()
fig.savefig('example.png')
This can be done using:
plt.figure(figsize=(15,8))
sns.kdeplot(data,shade=True)
In addition to elz answer regarding "figure level" methods that return multi-plot grid objects it is possible to set the figure height and width explicitly (that is without using aspect ratio) using the following approach:
import seaborn as sns
g = sns.catplot(data=df, x='xvar', y='yvar', hue='hue_bar')
g.fig.set_figwidth(8.27)
g.fig.set_figheight(11.7)
This shall also work.
from matplotlib import pyplot as plt
import seaborn as sns
plt.figure(figsize=(15,16))
sns.countplot(data=yourdata, ...)
For my plot (a sns factorplot) the proposed answer didn't works fine.
Thus I use
plt.gcf().set_size_inches(11.7, 8.27)
Just after the plot with seaborn (so no need to pass an ax to seaborn or to change the rc settings).
See How to change the image size for seaborn.objects for a solution with the new seaborn.objects interface from seaborn v0.12, which is not the same as seaborn axes-level or figure-level plots.
Adjusting the size of the plot depends if the plot is a figure-level plot like seaborn.displot, or an axes-level plot like seaborn.histplot. This answer applies to any figure or axes level plots.
See the the seaborn API reference
seaborn is a high-level API for matplotlib, so seaborn works with matplotlib methods
Tested in python 3.8.12, matplotlib 3.4.3, seaborn 0.11.2
Imports and Data
import seaborn as sns
import matplotlib.pyplot as plt
# load data
df = sns.load_dataset('penguins')
sns.displot
The size of a figure-level plot can be adjusted with the height and/or aspect parameters
Additionally, the dpi of the figure can be set by accessing the fig object and using .set_dpi()
p = sns.displot(data=df, x='flipper_length_mm', stat='density', height=4, aspect=1.5)
p.fig.set_dpi(100)
Without p.fig.set_dpi(100)
With p.fig.set_dpi(100)
sns.histplot
The size of an axes-level plot can be adjusted with figsize and/or dpi
# create figure and axes
fig, ax = plt.subplots(figsize=(6, 5), dpi=100)
# plot to the existing fig, by using ax=ax
p = sns.histplot(data=df, x='flipper_length_mm', stat='density', ax=ax)
Without dpi=100
With dpi=100
# Sets the figure size temporarily but has to be set again the next plot
plt.figure(figsize=(18,18))
sns.barplot(x=housing.ocean_proximity, y=housing.median_house_value)
plt.show()
Some tried out ways:
import seaborn as sns
import matplotlib.pyplot as plt
ax, fig = plt.subplots(figsize=[15,7])
sns.boxplot(x="feature1", y="feature2",data=df) # where df would be your dataframe
or
import seaborn as sns
import matplotlib.pyplot as plt
plt.figure(figsize=[15,7])
sns.boxplot(x="feature1", y="feature2",data=df) # where df would be your dataframe
The top answers by Paul H and J. Li do not work for all types of seaborn figures. For the FacetGrid type (for instance sns.lmplot()), use the size and aspect parameter.
Size changes both the height and width, maintaining the aspect ratio.
Aspect only changes the width, keeping the height constant.
You can always get your desired size by playing with these two parameters.
Credit: https://stackoverflow.com/a/28765059/3901029

Seaborn pairplot legend don't show colors and labels

I'm using seaborn 0.11.2 but I have troubles seeing the legend of the seaborn pairplot.
Here is the code: all is working fine except for the legend
for x in x1_categorical:
plt.figure()
sns.pairplot(data=x1[[x,'weight']],hue=x, palette='husl', height=4, aspect=4)
plt.title(x)
I cannot see neither color or labels. I have already tried what suggested here: Seaborn Pairplot Legend Not Showing Colors
I have no clue, thanks in advance!
If I understand it correctly, x1_categorical contains categorical column names. Taking seaborn's penguin dataset as an example, the current code would look like:
from matplotlib import pyplot as plt
import seaborn as sns
x1 = sns.load_dataset('penguins')
x1_categorical = ['species', 'island', 'sex']
for x in x1_categorical:
g = sns.pairplot(data=x1[[x, 'body_mass_g']], hue=x, palette='husl', height=4, aspect=3)
plt.title(x)
plt.tight_layout()
When I try this (seaborn 0.11.2), I get plots such as:
These seem to be kdeplots for the numerical column, using the categorical column as hue. Unfortunately, the legends are empty, also when plt.legend() is tried.
An alternative is to explicitly create the kdeplots, for example:
from matplotlib import pyplot as plt
import seaborn as sns
x1 = sns.load_dataset('penguins')
x1_categorical = ['species', 'island', 'sex']
fig, axs = plt.subplots(ncols=1, nrows=len(x1_categorical), figsize=(12, 4*len(x1_categorical)))
for ax, x in zip(axs, x1_categorical):
sns.kdeplot(data=x1, x='body_mass_g', hue=x, palette='husl', fill=True, common_norm=False, ax=ax)
sns.despine()
The example code creates one large figure, but if needed, separate plots could be created as well.
An alternative could use common_norm=True, multiple='stack':

Plot another point on top of swarmplot

I want to plot a "highlighted" point on top of swarmplot like this
The swarmplot don't have the y-axis, so I have no idea how to plot that point.
import seaborn as sns
sns.set(style="whitegrid")
tips = sns.load_dataset("tips")
ax = sns.swarmplot(x=tips["total_bill"])
This approach is predicated on knowing the index of the data point you wish to highlight, but it should work - although if you have multiple swarmplots on a single Axes instance it will become slightly more complex.
import matplotlib.pyplot as plt
import matplotlib
import seaborn as sns
sns.set(style="whitegrid")
tips = sns.load_dataset("tips")
ax = sns.swarmplot(x=tips["total_bill"])
artists = ax.get_children()
offsets = []
for a in artists:
if type(a) is matplotlib.collections.PathCollection:
offsets = a.get_offsets()
break
plt.scatter(offsets[50,0], offsets[50,1], marker='o', color='orange', zorder=10)
You can highlight a point/s using the hue attribute if you add a grouping variable for the y axis (so that they appear as a single group), and then use another variable to highlight the point that you're interested in.
Then you can remove the y labels and styling and legend.
import matplotlib.pyplot as plt
import seaborn as sns
sns.set(style="whitegrid")
# Get data and mark point you want to highlight
tips = sns.load_dataset("tips")
tips['highlighted_point'] = 0
tips.loc[tips[tips.total_bill > 50].index, 'highlighted_point'] = 1
# Add holding 'group' variable so they appear as one
tips['y_variable'] = 'testing'
# Use 'hue' to differentiate the highlighted point
ax = sns.swarmplot(x=tips["total_bill"], y=tips['y_variable'], hue=tips['highlighted_point'])
# Remove legend
ax.get_legend().remove()
# Hide y axis formatting
ax.set_ylabel('')
ax.get_yaxis().set_ticks([])
plt.show()

How to subplot seaborn catplot (kind='count') on-top of catplot (kind='violin') with sharex=True

So far I have tried the following code:
# Import to handle plotting
import seaborn as sns
# Import pyplot, figures inline, set style, plot pairplot
import matplotlib.pyplot as plt
# Make the figure space
fig = plt.figure(figsize=(2,4))
gs = fig.add_gridspec(2, 4)
ax1 = fig.add_subplot(gs[0, :])
ax2 = fig.add_subplot(gs[1, :])
# Load the example car crash dataset
tips = sns.load_dataset("tips")
# Plot the frequency counts grouped by time
sns.catplot(x='sex', hue='smoker',
kind='count',
col='time',
data=tips,
ax=ax1)
# View the data
sns.catplot(x='sex', y='total_bill', hue='smoker',
kind='violin',
col='time',
split='True',
cut=0,
bw=0.25,
scale='area',
scale_hue=False,
inner='quartile',
data=tips,
ax=ax2)
plt.close(2)
plt.close(3)
plt.show()
This seems to stack the categorial plots, of each kind respectively, on top of eachother.
What I want are the resulting plots of the following code in a single figure with the countplot in row one and the violin plot in row two.
# Import to handle plotting
import seaborn as sns
# Import pyplot, figures inline, set style, plot pairplot
import matplotlib.pyplot as plt
# Load the example car crash dataset
tips = sns.load_dataset("tips")
# Plot the frequency counts grouped by time
sns.catplot(x='sex', hue='smoker',
kind='count',
col='time',
data=tips)
# View the data
sns.catplot(x='sex', y='total_bill', hue='smoker',
kind='violin',
col='time',
split='True',
cut=0,
bw=0.25,
scale='area',
scale_hue=False,
inner='quartile',
data=tips)
The actual categorical countplot that I would like to span row one of a figure that also contains a categorical violin plot (Ref. Image 3):
The actual categorical violin plot that I would like to span row two of a figure that also contains a categorical countplot (Ref. Image 2):
I tried the following code which forced the plots to be in the same figure. The downside is that the children of the figure/axes did not transfer, i.e. axis-labels, legend, and grid lines. I feel pretty close with this hack but need another push or source for inspiration. Also, I'm no longer able to close the old/unwanted figures.
# Import to handle plotting
import seaborn as sns
# Import pyplot, figures inline, set style, plot pairplot
import matplotlib.pyplot as plt
# Set some style
sns.set_style("whitegrid")
# Load the example car crash dataset
tips = sns.load_dataset("tips")
# Plot the frequency counts grouped by time
a = sns.catplot(x='sex', hue='smoker',
kind='count',
col='time',
data=tips)
numSubs_A = len(a.col_names)
for i in range(numSubs_A):
for p in a.facet_axis(0,i).patches:
a.facet_axis(0,i).annotate(str(p.get_height()), (p.get_x()+0.15, p.get_height()+0.1))
# View the data
b = sns.catplot(x='sex', y='total_bill', hue='smoker',
kind='violin',
col='time',
split='True',
cut=0,
bw=0.25,
scale='area',
scale_hue=False,
inner='quartile',
data=tips)
numSubs_B = len(b.col_names)
# Subplots migration
f = plt.figure()
for i in range(numSubs_A):
f._axstack.add(f._make_key(a.facet_axis(0,i)), a.facet_axis(0,i))
for i in range(numSubs_B):
f._axstack.add(f._make_key(b.facet_axis(0,i)), b.facet_axis(0,i))
# Subplots size adjustment
f.axes[0].set_position([0,1,1,1])
f.axes[1].set_position([1,1,1,1])
f.axes[2].set_position([0,0,1,1])
f.axes[3].set_position([1,0,1,1])
It is in general not possible to combine the output of several seaborn figure-level functions into a single figure. See (this question, also this issue). I once wrote a hack to externally combine such figures, but it has several drawbacks. Feel free to use it if it works for you.
But in general, consider creating the plot you desired manually. In this case it could look like this:
import seaborn as sns
import matplotlib.pyplot as plt
sns.set()
fig, axes = plt.subplots(2,2, figsize=(8,6), sharey="row", sharex="col")
tips = sns.load_dataset("tips")
order = tips["sex"].unique()
hue_order = tips["smoker"].unique()
for i, (n, grp) in enumerate(tips.groupby("time")):
sns.countplot(x="sex", hue="smoker", data=grp,
order=order, hue_order=hue_order, ax=axes[0,i])
sns.violinplot(x='sex', y='total_bill', hue='smoker', data=grp,
order=order, hue_order=hue_order,
split='True', cut=0, bw=0.25,
scale='area', scale_hue=False, inner='quartile',
ax=axes[1,i])
axes[0,i].set_title(f"time = {n}")
axes[0,0].get_legend().remove()
axes[1,0].get_legend().remove()
axes[1,1].get_legend().remove()
plt.show()
seaborn.catplot does not accept an "ax" argument, hence the problem with your first code.
It appears that some hacking is needed to accomplish the x-sharing you aim for:
How to plot multiple Seaborn Jointplot in Subplot
As such, you could save the time and effort, and just manually stack the two figures from your second code.

Rotate label text in seaborn factorplot

I have a simple factorplot
import seaborn as sns
g = sns.factorplot("name", "miss_ratio", "policy", dodge=.2,
linestyles=["none", "none", "none", "none"], data=df[df["level"] == 2])
The problem is that the x labels all run together, making them unreadable. How do you rotate the text so that the labels are readable?
I had a problem with the answer by #mwaskorn, namely that
g.set_xticklabels(rotation=30)
fails, because this also requires the labels. A bit easier than the answer by #Aman is to just add
plt.xticks(rotation=45)
You can rotate tick labels with the tick_params method on matplotlib Axes objects. To provide a specific example:
ax.tick_params(axis='x', rotation=90)
This is still a matplotlib object. Try this:
# <your code here>
locs, labels = plt.xticks()
plt.setp(labels, rotation=45)
Any seaborn plots suported by facetgrid won't work with (e.g. catplot)
g.set_xticklabels(rotation=30)
however barplot, countplot, etc. will work as they are not supported by facetgrid. Below will work for them.
g.set_xticklabels(g.get_xticklabels(), rotation=30)
Also, in case you have 2 graphs overlayed on top of each other, try set_xticklabels on graph which supports it.
If anyone wonders how to this for clustermap CorrGrids (part of a given seaborn example):
import seaborn as sns
import matplotlib.pyplot as plt
sns.set(context="paper", font="monospace")
# Load the datset of correlations between cortical brain networks
df = sns.load_dataset("brain_networks", header=[0, 1, 2], index_col=0)
corrmat = df.corr()
# Set up the matplotlib figure
f, ax = plt.subplots(figsize=(12, 9))
# Draw the heatmap using seaborn
g=sns.clustermap(corrmat, vmax=.8, square=True)
rotation = 90
for i, ax in enumerate(g.fig.axes): ## getting all axes of the fig object
ax.set_xticklabels(ax.get_xticklabels(), rotation = rotation)
g.fig.show()
You can also use plt.setp as follows:
import matplotlib.pyplot as plt
import seaborn as sns
plot=sns.barplot(data=df, x=" ", y=" ")
plt.setp(plot.get_xticklabels(), rotation=90)
to rotate the labels 90 degrees.
For a seaborn.heatmap, you can rotate these using (based on #Aman's answer)
pandas_frame = pd.DataFrame(data, index=names, columns=names)
heatmap = seaborn.heatmap(pandas_frame)
loc, labels = plt.xticks()
heatmap.set_xticklabels(labels, rotation=45)
heatmap.set_yticklabels(labels[::-1], rotation=45) # reversed order for y
One can do this with matplotlib.pyplot.xticks
import matplotlib.pyplot as plt
plt.xticks(rotation = 'vertical')
# Or use degrees explicitly
degrees = 70 # Adjust according to one's preferences/needs
plt.xticks(rotation=degrees)
Here one can see an example of how it works.
Use ax.tick_params(labelrotation=45). You can apply this to the axes figure from the plot without having to provide labels. This is an alternative to using the FacetGrid if that's not the path you want to take.
If the labels have long names it may be hard to get it right. A solution that worked well for me using catplot was:
import matplotlib.pyplot as plt
fig = plt.gcf()
fig.autofmt_xdate()

Categories