Wuff
Wuff

Reputation: 267

How to remove whitespace on top and bottom of seaborn scatterplots

Scatterplots with many ticks on the y-axis have a large whitespace on the top and on the bottom as you can see with the gridlines. How to remove whitespace on top and bottom of seaborn scatterplot?

scatterplot

The code for a minimal working example:

import matplotlib.pyplot as plt
import seaborn as sns

data = sns.load_dataset("car_crashes")

plt.figure(figsize=(5, 15))
sns.set_style("whitegrid")
sns.scatterplot(
    data=data,
    x='alcohol',
    y='abbrev',
    size='ins_losses',
    legend=False,
)

plt.show()

Upvotes: 4

Views: 1580

Answers (2)

plt.margins(0.015, tight=True)

The above worked really well for me.

This removes the whitespace/margin in the graph.

Note that the number doesn't have to be 0.015, so adjust it to suit your needs.

Upvotes: 0

Matt Hall
Matt Hall

Reputation: 8152

If you switch to the object oriented plotting style, passing ax around, you can easily get at the tick positions. Then you can adjust the spacing at the ends to whatever you like, e.g. by changing the 2 in the code below. I think doing it this way reduces the guesswork, because you're adjusting to a proportion of the tick interval. You'll also get sensible results no matter how many rows you're plotting.

For example, here's how I'd go about it (using fewer states to make the plot a bit smaller):

import matplotlib.pyplot as plt
import seaborn as sns
sns.set_style("whitegrid")

# Get some example data.
data = sns.load_dataset("car_crashes")

# Make the plot.
fig, ax = plt.subplots(figsize=(5, 5))
sc = sns.scatterplot(data=data[:15],
                     x='alcohol',
                     y='abbrev',
                     size='ins_losses',
                     legend=False,
                     ax=ax,
                    )

# Get the first two and last y-tick positions.
miny, nexty, *_, maxy = ax.get_yticks()

# Compute half the y-tick interval (for example).
eps = (nexty - miny) / 2  # <-- Your choice.

# Adjust the limits.
ax.set_ylim(maxy+eps, miny-eps)

plt.show()

This gives:

enter image description here

Upvotes: 2

Related Questions