Seaborn - 从 DataFrame 直方图中删除间距

aso*_*uin 3 python pandas seaborn

我正在尝试从seaborn通过该DataFrame.hist方法启用的 DataFrame 生成直方图,但我不断发现在直方图本身的任一侧添加了额外的空间,如下图中的红色箭头所示: 带有额外间距的直方图

如何删除这些空格?重现此图的代码如下:

import seaborn as sns
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt

from random import seed, choice
seed(0)

df = pd.DataFrame([choice(range(250)) for _ in range(100)], columns=['Values'])

bins = np.arange(0, 260, 10)

df['Values'].hist(bins=bins)
plt.tight_layout()
plt.show()
Run Code Online (Sandbox Code Playgroud)

Jör*_*ees 7

plt.tight_layout() 仅对绘图的“外边距”有效(刻度线、斧头标签等)。

默认情况下,matplotlib 的 hist 会在 hist 条形图周围留下一个内边距。要禁用,您可以执行以下操作:

ax = df['Values'].hist(bins=bins)
ax.margins(x=0)
plt.show()
Run Code Online (Sandbox Code Playgroud)