【问题标题】:How to remove whitespace on top and bottom of seaborn scatterplots如何删除seaborn散点图顶部和底部的空格
【发布时间】:2021-09-30 13:19:16
【问题描述】:

在 y 轴上有许多刻度的散点图在顶部和底部都有很大的空白,正如您在网格线中看到的那样。如何去除seaborn散点图顶部和底部的空白?

一个最小工作示例的代码:

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

【问题讨论】:

  • 我正在研究它,看起来你可以调整边距。 plt.margins(0.015, tight=True)
  • @r-beginners 感谢它的工作原理:) 0.015 是猜测工作,对吧?因为我意识到当将其设置为零时,点会被切断。最好的解决方案是边距与 y 刻度之间的空间相同。
  • 您可以通过运行ax = sns.scatterplot(...); ax.get_ylim() 查看 y 轴上使用的单位。而你想要的是ax.set_ylim(-1, len(data['abbrev']))
  • 是的,我猜。我根据您的评论做了一些研究,发现了一些很棒的人responses。将此代码应用于您的代码的结果使我得到了 0.02 的正确间距。

标签: python matplotlib seaborn scatter-plot


【解决方案1】:

如果您切换到面向对象的绘图样式,传递ax,您可以轻松获得刻度位置。然后您可以将末端的间距调整为您喜欢的任何值,例如通过更改下面代码中的2。我认为这样做可以减少猜测,因为您正在调整刻度间隔的一部分。无论您绘制多少行,您都将获得合理的结果。

例如,我会这样做(使用更少的状态使情节更小):

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

这给出了:

【讨论】:

  • 非常感谢!奇迹般有效!很高兴它也适用于 x 轴(似乎也有不同的边距),只需使用 ax.get_xticks()ax.set_xlim()