Skip to main content
 首页 » 编程设计

python之如何在 pyplot.hist2d 的每个 "cell"中绘制点的百分比

2024年10月17日7落叶无声

我希望直方图的每个“单元格”都有一个数字代表该“单元格”中总点的百分比,而不是颜色。除了以编程方式生成矩阵之外,还有其他方法吗? 2D histogram of my data

关于 M.T的建议,我认为 seaborn.heatmap() 要求一个二维数据数组。但是我有两个一维数组(比如高度和体重,每个数据点都是一个具有(高度,体重)值的人。代码在这里:)并且数组值没有特定的顺序。此处示例代码:

plt.hist2d(height, weight, (20, 50), range=np.array([(0, 200), (0, 500)]), cmap=plt.cm.Paired) 
plt.colorbar() 
plt.show() 

请您参考如下方法:

您可以使用文本并循环输出到规范的 hist2d,如下所示,

import numpy as np 
import matplotlib.pyplot as plt 
 
height = [102, 99, 153, 98, 142, 198, 99] 
weight = [201, 192, 295, 181, 315, 311, 181] 
 
counts, xedges, yedges, Image = plt.hist2d(height, weight, (20, 50),  
                                           range=np.array([(0, 200), (0, 500)]),  
                                           cmap=plt.cm.Paired, normed=True) 
 
dx = xedges[2]-xedges[1] 
dy = yedges[2]-yedges[1] 
for i in range(xedges.size-1): 
    for j in range(yedges.size-1): 
        xb = xedges[i] + 0.25*dx 
        yb = yedges[j] + 0.25*dy  
        plt.text(xb, yb, str(np.round(100.*counts[i,j],2)), fontsize=6 ) 
 
plt.show() 

这给出了,