Cannot get histogram to show separated bins with vertical lines
Using your example:
import numpy as npimport matplotlib.pyplot as pltx = np.random.rand((100)) bins = np.linspace(0, 2, 40)plt.title('Relative Amplitude',fontsize=30)plt.xlabel('Random Histogram')plt.ylabel('Frequency',fontsize=30)plt.hist(x, bins, alpha=0.5, histtype='bar', ec='black')plt.legend(loc='upper right',fontsize=30)plt.xticks(fontsize = 20) plt.yticks(fontsize = 20) plt.show()
Which produces the following image:
The key difference is the use of the ec
keyword argument. This is short for "edgecolor". In the documentation for plt.hist
it says that in addition to all of the listed keyword arguments, plt.hist
also takes keyword arguments for the Patch
initializer. edgecolor
is one of those keyword arguments. That's why it's not explicitly listed in the documentation for plt.hist
. All of the bars in the plot are an individual Patch
object, so you're saying you want all of the bars to be drawn with a black outline (or edgecolor
in matplotlib jargon).
It works for me if I give different colors to the edgecolor
argument and the color
argument.For example:
import numpy as npimport matplotlib.pyplot as pltx = np.random.rand((100)) bins = np.linspace(0, 2, 40)plt.title('Relative Amplitude',fontsize=30)plt.xlabel('Random Histogram')plt.ylabel('Frequency',fontsize=30)plt.hist(x, bins, alpha=0.5,edgecolor='black',color='steelblue', histtype='bar')plt.legend(loc='upper right',fontsize=30)plt.xticks(fontsize = 20) plt.yticks(fontsize = 20) plt.show()
You can use rwidth
Parameter in plt.hist
.Note I am using matplotlib version '3.4.2'.
rwidth : float or None, default: None The relative width of the bars as a fraction of the bin width. If None, automatically compute the width.
import numpy as npimport matplotlib.pyplot as pltx = np.random.rand((100)) bins = np.linspace(0, 2, 40)plt.title('Relative Amplitude',fontsize=30)plt.xlabel('Random Histogram', fontsize=30)plt.ylabel('Frequency',fontsize=30)plt.hist(x, bins, rwidth=0.6, alpha=0.5, histtype='bar')# rwidth specify the width of the bars# rwidth is an number between 0 and 1plt.xticks(fontsize=15) plt.yticks(fontsize=15)plt.xlim(0,1)plt.show()