Issue
I'm trying to plot an histogram with percetages above the bars, this is my actual code
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")
And this is the output: Histogram
Solution
As per the duplicate.
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")
Answered By - Trenton McKinney
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.