matplotlib 直方图中高于条形图的百分比[重复]

6g8kf2rb  于 2023-10-24  发布在  其他
关注(0)|答案(2)|浏览(136)

此问题已在此处有答案

How to add value labels on a bar chart(7个回答)
8天前关闭
我正试图绘制一个柱状图,柱状图上方有一个数字,这是我的实际代码

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()
plt.hist(Eventos)
plt.xlabel('Número de nombres, Número de apellidos')
plt.ylabel('Count')
plt.title('Histograma nombres generados\n\n',
        fontweight = "bold")

这是输出:Histogram

nwwlzxa7

nwwlzxa71#

根据副本。

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"]

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

plt.hist(Eventos)

# get the current axes and containers
c = plt.gca().containers[0]

# add the bar labels 
plt.bar_label(c, labels=[v.get_height()/len(Eventos) for v in c])
# plt.bar_label(c, fmt=lambda x: x/len(Eventos) if x > 0 else '')  # also works and doesn't annotate where the bar height is 0

# space between label and top of plot
plt.margins(y=0.1)

plt.xlabel('Número de nombres, Número de apellidos')
plt.ylabel('Count')
plt.title('Histograma nombres generados\n\n', fontweight = "bold")

相关问题