import matplotlib.pyplot as plt
import numpy as np
mu, sigma = 100, 15
x = mu + sigma * np.random.randn(10000)
hist, bins = np.histogram(x, bins=50)
width = 0.7 * (bins[1] - bins[0])
center = (bins[:-1] + bins[1:])/2
plt.bar(center, hist, align='center', width=width)
plt.show()
La interfaz orientada a objetos también es sencillo:
fig, ax = plt.subplots()
ax.bar(center, hist, align='center', width=width)
fig.savefig("1.png")
Si está utilizando personalizados contenedores (no constantes), puede pasar a calcular los anchos usando np.diff
, pase el ancho a ax.bar
y use ax.set_xticks
para etiquetar los bordes de la bandeja:
import matplotlib.pyplot as plt
import numpy as np
mu, sigma = 100, 15
x = mu + sigma * np.random.randn(10000)
bins = [0, 40, 60, 75, 90, 110, 125, 140, 160, 200]
hist, bins = np.histogram(x, bins=bins)
width = np.diff(bins)
center = (bins[:-1] + bins[1:])/2
fig, ax = plt.subplots(figsize=(8,3))
ax.bar(center, hist, align='center', width=width)
ax.set_xticks(bins)
fig.savefig("/tmp/out.png")
plt.show()
¿Hay una manera de pasar el bin bordes para el eje x de la gráfica de barras? – CMCDragonkai
@CMCDragonkai: el parámetro 'width' de' plt.bar' puede aceptar un objeto similar a una matriz (en lugar de un escalar). Por lo tanto, podría usar 'width = np.diff (bins)' en lugar de 'width = 0.7 * (bins [1] - bins [0])'. – unutbu
Pero el ajuste de 'ancho' por sí solo solo establece el ancho de la barra ¿no? Estoy hablando de las etiquetas del eje x (es decir, quiero ver que los bordes reales del contenedor sean etiquetas en el eje x). Debería ser similar a cómo funciona 'plt.hist'. – CMCDragonkai