You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Matplotlib直方图的柱子上方添加百分比

在直方图柱子上方显示百分比

以下是修改后的代码,实现柱子上方显示百分比的功能:

import matplotlib.pyplot as plt
from numpy import random

Nombres_de_Pila = ["Alejandro", "Eric", "Mari", "Ruben", "Daniela", "Ana", "Ximena", "Ramón", "Diego",
                   "Fernanda", "José", "Lucia", "Alondra", "Saul", "Pilar", "Luis", "Victoria", "Lucas","Beatriz", "Elisa" ]
Apellidos = ["Martorell","Barroso","Galiano","Nava","Alcaraz","Peña","Varela","Romero","Rincón","Pineda",
             "Acuña","Pino","Arjona","Jimenez","Maroto","Carranza","Bosch","Costa","Godoy","Lopez"]

Eventos = random.choice(["11","12","21","22","31","32"], p=[0.1, 0.3,0.05,0.5,0.02,0.03], size = 1000)
Eventos = Eventos.tolist()

# 绘制直方图,同时获取频数、区间和柱子对象
counts, bins, patches = plt.hist(Eventos)
total = len(Eventos)

# 遍历每个柱子,添加百分比文本
for i in range(len(counts)):
    # 计算百分比并格式化
    percentage = f"{(counts[i]/total)*100:.2f}%"
    # 获取柱子中心位置,设置文本的x坐标
    x = bins[i] + (bins[i+1] - bins[i])/2
    # 设置文本y坐标,添加小偏移避免和柱子顶部重叠
    y = counts[i] + 5
    plt.text(x, y, percentage, ha='center', fontsize=9)

plt.xlabel('姓名数量, 姓氏数量')
plt.ylabel('频数')
plt.title('生成姓名直方图\n\n', fontweight = "bold")
plt.show()

关键修改说明

  • 调用plt.hist()时接收返回值:counts是每个柱子的频数,bins是区间边界,用于定位文本位置
  • 以总样本数为基数,计算每个柱子的占比并格式化为百分比
  • 使用plt.text()在柱子顶部中心位置添加文本,通过ha='center'保证文本居中,小偏移量避免与柱子重叠

内容的提问来源于stack exchange,提问作者Eric Sebastián Sánchez Conde

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.08 08:39:56