Seaborn 通常不提供对其计算的访问,它只是尝试创建可视化。但您可以使用相同的基础函数来获取其结果。你需要bins = np.histogram_bin_edges(..., bins='auto') (or bins='fd'
强制使用 Freedman Diaconis 估计器)。进而sns.histplot(..., bins=bins)
对彼此而言。
import pandas as pd
import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt
from sklearn.datasets import load_boston
boston = load_boston()
df = pd.DataFrame(boston.data, columns=boston.feature_names)
bins = np.histogram_bin_edges(df['NOX'], bins='auto')
f, axs = plt.subplots(1, 2, figsize=(15, 4.5))
sns.histplot(df['NOX'], bins=bins, color='steelblue', ax=axs[0])
sns.histplot(df[df['CRIM'] > 10.73]['NOX'], bins=bins, color='darkgreen', ax=axs[1])
for ax in axs:
for p in ax.patches:
x, w, h = p.get_x(), p.get_width(), p.get_height()
if h > 0:
ax.text(x + w / 2, h, f'{h / len(df) * 100:.2f}%\n', ha='center', va='center', size=8)
ax.margins(y=0.07)
plt.show()