Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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()
like image 734
Wuff Avatar asked Sep 07 '25 21:09

Wuff


1 Answers

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

like image 85
Matt Hall Avatar answered Sep 09 '25 15:09

Matt Hall