通过seaborn histplot绘图时如何打印绘图上每个bin的值

问题描述 投票:0回答:1

假设我正在使用以下代码绘制直方图, 有没有办法在绘图上打印每个 bin 的值(基本上是每个条形的高度)?

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

# Fixing random state for reproducibility
np.random.seed(19680801)

x, y = np.random.rand(2, 100) * 4
sns.histplot(x=x, y=y, bins=4, binrange=[[0, 4], [0, 4]])

我基本上想要有这样的情节:

python seaborn
1个回答
0
投票

我不确定这对于seaborn是否可行(或者至少在不使用numpy/matplotlib再次单独计算直方图的情况下不可能)。因此,如果您不依赖seaborn,您可以考虑使用 matplotlib 的 hist2d 来代替:

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

# Fixing random state for reproducibility
np.random.seed(19680801)

x, y = np.random.rand(2, 100) * 4
hist, xedges, yedges, _ = plt.hist2d(x, y, bins=4, range=[[0, 4], [0, 4]])

for i in range(len(h)):
    for j in range(len(h[i])):
        plt.text(xedges[i] + (xedges[i + 1] - xedges[i]) / 2,
                 yedges[j] + (yedges[j + 1] - yedges[j]) / 2,
                 hist[i][j], ha="center", va="center", color="w")

plt.show()

© www.soinside.com 2019 - 2024. All rights reserved.