Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Seaborn despine() brings back the ytick labels

Tags:

seaborn

Here is a code snippet

tips = sns.load_dataset("tips")
g = sns.FacetGrid(tips, col = 'time')
g = g.map(plt.hist, "tip")

with the following output

enter image description here

I want to introduce despine offset to these plots while keeping the rest unchanged. Therefore, I inserted the despine function in the existing code:

tips = sns.load_dataset("tips")
g = sns.FacetGrid(tips, col = 'time')
g.despine(offset=10)
g = g.map(plt.hist, "tip")

which results in the following plots

enter image description here

As a result, the offset is applied to the axes. However, the ytick labels on the right plot are back, which I don't want.

Could anyone help me on this?

like image 557
Debapriya Das Avatar asked Nov 08 '22 13:11

Debapriya Das


1 Answers

To remove the yaxis tick labels, you can use the code below:

The libs:

import seaborn as sns
sns.set_style('ticks')

The adjusted code:

tips = sns.load_dataset("tips")
g = sns.FacetGrid(tips, col = 'time')
g.despine(offset=10)
g = g.map(plt.hist, "tip")

# IMPORTANT: I assume that you use colwrap=None in FacetGrid constructor
# loop over the non-left axes:
for ax in g.axes[:, 1:].flat:
    # get the yticklabels from the axis and set visibility to False
    for label in ax.get_yticklabels():
        label.set_visible(False)
    ax.yaxis.offsetText.set_visible(False)

enter image description here

A bit more general, image you now have a 2x2 FacetGrid, you want to despine with an offset, but the x- and yticklabels return:

enter image description here

Remove them all using this code:

tips = sns.load_dataset("tips")
g = sns.FacetGrid(tips, col = 'time', row='sex')
g.despine(offset=10)
g = g.map(plt.hist, "tip")

# IMPORTANT: I assume that you use colwrap=None in FacetGrid constructor
# loop over the non-left axes:
for ax in g.axes[:, 1:].flat:
    # get the yticklabels from the axis and set visibility to False
    for label in ax.get_yticklabels():
        label.set_visible(False)
    ax.yaxis.offsetText.set_visible(False)

# loop over the top axes:
for ax in g.axes[:-1, :].flat:
    # get the xticklabels from the axis and set visibility to False
    for label in ax.get_xticklabels():
        label.set_visible(False)
    ax.xaxis.offsetText.set_visible(False)

enter image description here

UPDATE:

for completeness, mwaskom (ref to github issue) gave an explanation why this issue is occuring:

So this happens because matplotlib calls axis.reset_ticks() internally when moving the spine. Otherwise, the spine gets moved but the ticks stay in the same place. It's not configurable in matplotlib and, even if it were, I don't know if there is a public API for moving individual ticks. Unfortunately I think you'll have to remove the tick labels yourself after offsetting the spines.

like image 152
Daan Avatar answered Dec 04 '22 10:12

Daan