Plotting Histogram in Python using Matplotlib - GeeksforGeeks

29 Jul, 2021
A histogram is basically used to represent data provided in a form of some groups.It is accurate method for the graphical representation of numerical data distribution.It is a type of bar plot where X-axis represents the bin ranges while Y-axis gives information about frequency.
To create a histogram the first step is to create bin of the ranges, then distribute the whole range of the values into a series of intervals, and count the values which fall into each of the intervals.Bins are clearly identified as consecutive, non-overlapping intervals of variables.The matplotlib.pyplot.hist() function is used to compute and create histogram of x. 
The following table shows the parameters accepted by matplotlib.pyplot.hist() function : 
Let’s create a basic histogram of some random values. Below code creates a simple histogram of some random values:  
Python3
from matplotlib import pyplot as pltimport numpy as np  # Creating dataseta = np.array([22, 87, 5, 43, 56,              73, 55, 54, 11,              20, 51, 5, 79, 31,              27]) # Creating histogramfig, ax = plt.subplots(figsize =(10, 7))ax.hist(a, bins = [0, 25, 50, 75, 100]) # Show plotplt.show()
Output : 
Matplotlib provides a range of different methods to customize histogram. matplotlib.pyplot.hist() function itself provides many attributes with the help of which we can modify a histogram.The hist() function provide a patches object which gives access to the properties of the created objects, using this we can modify the plot according to our will.
Example 1:  
Python3
import matplotlib.pyplot as pltimport numpy as npfrom matplotlib import colorsfrom matplotlib.ticker import PercentFormatter # Creating datasetnp.random.seed(23685752)N_points = 10000n_bins = 20 # Creating distributionx = np.random.randn(N_points)y = .8 ** x + np.random.randn(10000) + 25 # Creating histogramfig, axs = plt.subplots(1, 1,                        figsize =(10, 7),                        tight_layout = True) axs.hist(x, bins = n_bins) # Show plotplt.show()
Output : 
Example 2: The code below modifies the above histogram for a better view and accurate readings. 
Python3
import matplotlib.pyplot as pltimport numpy as npfrom matplotlib import colorsfrom matplotlib.ticker import PercentFormatter  # Creating datasetnp.random.seed(23685752)N_points = 10000n_bins = 20 # Creating distributionx = np.random.randn(N_points)y = .8 ** x + np.random.randn(10000) + 25legend = ['distribution'] # Creating histogramfig, axs = plt.subplots(1, 1,                        figsize =(10, 7),                        tight_layout = True)  # Remove axes splinesfor s in ['top', 'bottom', 'left', 'right']:    axs.spines[s].set_visible(False) # Remove x, y ticksaxs.xaxis.set_ticks_position('none')axs.yaxis.set_ticks_position('none')   # Add padding between axes and labelsaxs.xaxis.set_tick_params(pad = 5)axs.yaxis.set_tick_params(pad = 10) # Add x, y gridlinesaxs.grid(b = True, color ='grey',        linestyle ='-.', linewidth = 0.5,        alpha = 0.6) # Add Text watermarkfig.text(0.9, 0.15, 'Jeeteshgavande30',         fontsize = 12,         color ='red',         ha ='right',         va ='bottom',         alpha = 0.7) # Creating histogramN, bins, patches = axs.hist(x, bins = n_bins) # Setting colorfracs = ((N**(1 / 5)) / N.max())norm = colors.Normalize(fracs.min(), fracs.max()) for thisfrac, thispatch in zip(fracs, patches):    color = plt.cm.viridis(norm(thisfrac))    thispatch.set_facecolor(color) # Adding extra features   plt.xlabel("X-axis")plt.ylabel("y-axis")plt.legend(legend)plt.title('Customized histogram') # Show plotplt.show()
Output : 
 
simmytarika5
Matplotlib Pyplot-class
Python-matplotlib
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Read JSON file using Python
Adding new column to existing DataFrame in Pandas
Python map() function
How to get column names in Pandas dataframe
Python Dictionary
Taking input in Python
Read a file line by line in Python
Enumerate() in Python
How to Install PIP on Windows ?
Iterate over a list in Python