If you want a histogram, you don't need to attach any 'names' to x-values because:

  • on x-axis you will have data bins
  • on y-axis counts (by default) or frequencies (density=True)
import matplotlib.pyplot as plt
import numpy as np
%matplotlib inline

np.random.seed(42)
x = np.random.normal(size=1000)

plt.hist(x, density=True, bins=30)  # density=False would make counts
plt.ylabel('Probability')
plt.xlabel('Data');

Note, the number of bins=30 was chosen arbitrarily, and there is Freedman–Diaconis rule to be more scientific in choosing the "right" bin width:

, where IQR is Interquartile range and n is total number of datapoints to plot

So, according to this rule one may calculate number of bins as:

q25, q75 = np.percentile(x, [25, 75])
bin_width = 2 * (q75 - q25) * len(x) ** (-1/3)
bins = round((x.max() - x.min()) / bin_width)
print("Freedman–Diaconis number of bins:", bins)
plt.hist(x, bins=bins);

Freedman–Diaconis number of bins: 82

And finally you can make your histogram a bit fancier with PDF line, titles, and legend:

import scipy.stats as st

plt.hist(x, density=True, bins=82, label="Data")
mn, mx = plt.xlim()
plt.xlim(mn, mx)
kde_xs = np.linspace(mn, mx, 300)
kde = st.gaussian_kde(x)
plt.plot(kde_xs, kde.pdf(kde_xs), label="PDF")
plt.legend(loc="upper left")
plt.ylabel("Probability")
plt.xlabel("Data")
plt.title("Histogram");

If you're willing to explore other opportunities, there is a shortcut with seaborn:

# !pip install seaborn
import seaborn as sns
sns.displot(x, bins=82, kde=True);

Now back to the OP.

If you have limited number of data points, a bar plot would make more sense to represent your data. Then you may attach labels to x-axis:

x = np.arange(3)
plt.bar(x, height=[1,2,3])
plt.xticks(x, ['a','b','c']);

Answer from Sergey Bushmanov on Stack Overflow
🌐
Matplotlib
matplotlib.org › stable › gallery › statistics › hist.html
Histograms — Matplotlib 3.11.2 documentation
Go to the end to download the full example code. How to plot histograms with Matplotlib.
🌐
W3Schools
w3schools.com › python › matplotlib_histograms.asp
Matplotlib Histograms
You can read from the histogram that there are approximately: 2 people from 140 to 145cm 5 people from 145 to 150cm 15 people from 151 to 156cm 31 people from 157 to 162cm 46 people from 163 to 168cm 53 people from 168 to 173cm 45 people from 173 to 178cm 28 people from 179 to 184cm 21 people from 185 to 190cm 4 people from 190 to 195cm · In Matplotlib, we use the hist() function to create histograms.
🌐
Matplotlib
matplotlib.org › stable › api › _as_gen › matplotlib.pyplot.hist.html
matplotlib.pyplot.hist — Matplotlib 3.11.2 documentation
This method uses numpy.histogram to bin the data in x and count the number of values in each bin, then draws the distribution either as a BarContainer or Polygon. The bins, range, density, and weights parameters are forwarded to numpy.histogram.
🌐
GeeksforGeeks
geeksforgeeks.org › data visualization › plotting-histogram-in-python-using-matplotlib
Plotting Histogram in Python using Matplotlib - GeeksforGeeks
A histogram can be customized by modifying its appearance with colors, gridlines, legends and other visual elements. This helps create more informative and visually appealing charts. ... import matplotlib.pyplot as plt import numpy as np from matplotlib import colors from matplotlib.ticker import PercentFormatter np.random.seed(23685752) N_points = 10000 n_bins = 20 x = np.random.randn(N_points) y = 0.8 ** x + np.random.randn(N_points) + 25 legend = ['distribution'] fig, axs = plt.subplots(1, 1, figsize=(10, 7), tight_layout=True) for s in ['top', 'bottom', 'left', 'right']: axs.spines[s].set_
Published: July 16, 2026
Top answer
1 of 7
301

If you want a histogram, you don't need to attach any 'names' to x-values because:

  • on x-axis you will have data bins
  • on y-axis counts (by default) or frequencies (density=True)
import matplotlib.pyplot as plt
import numpy as np
%matplotlib inline

np.random.seed(42)
x = np.random.normal(size=1000)

plt.hist(x, density=True, bins=30)  # density=False would make counts
plt.ylabel('Probability')
plt.xlabel('Data');

Note, the number of bins=30 was chosen arbitrarily, and there is Freedman–Diaconis rule to be more scientific in choosing the "right" bin width:

, where IQR is Interquartile range and n is total number of datapoints to plot

So, according to this rule one may calculate number of bins as:

q25, q75 = np.percentile(x, [25, 75])
bin_width = 2 * (q75 - q25) * len(x) ** (-1/3)
bins = round((x.max() - x.min()) / bin_width)
print("Freedman–Diaconis number of bins:", bins)
plt.hist(x, bins=bins);

Freedman–Diaconis number of bins: 82

And finally you can make your histogram a bit fancier with PDF line, titles, and legend:

import scipy.stats as st

plt.hist(x, density=True, bins=82, label="Data")
mn, mx = plt.xlim()
plt.xlim(mn, mx)
kde_xs = np.linspace(mn, mx, 300)
kde = st.gaussian_kde(x)
plt.plot(kde_xs, kde.pdf(kde_xs), label="PDF")
plt.legend(loc="upper left")
plt.ylabel("Probability")
plt.xlabel("Data")
plt.title("Histogram");

If you're willing to explore other opportunities, there is a shortcut with seaborn:

# !pip install seaborn
import seaborn as sns
sns.displot(x, bins=82, kde=True);

Now back to the OP.

If you have limited number of data points, a bar plot would make more sense to represent your data. Then you may attach labels to x-axis:

x = np.arange(3)
plt.bar(x, height=[1,2,3])
plt.xticks(x, ['a','b','c']);

2 of 7
27

If you haven't installed matplotlib yet just try the command.

> pip install matplotlib

Library import

import matplotlib.pyplot as plot

The histogram data:

plot.hist(weightList,density=1, bins=20) 
plot.axis([50, 110, 0, 0.06]) 
#axis([xmin,xmax,ymin,ymax])
plot.xlabel('Weight')
plot.ylabel('Probability')

Display histogram

plot.show()

And the output is like :

🌐
Python Graph Gallery
python-graph-gallery.com › histogram
Python Histogram Gallery | Dozens of examples with code
Pandas is not the most common Python library to build histograms, but it can be used to build decent ones. It provides different functions like hist() and plot() from matplotlib. The examples below should help you to get started with basic pandas histograms.
🌐
Matplotlib
matplotlib.org › stable › gallery › statistics › histogram_multihist.html
The histogram (hist) function with multiple data sets — Matplotlib 3.11.2 documentation
Go to the end to download the full example code. Plot histogram with multiple sample sets and demonstrate: ... Selecting different bin counts and sizes can significantly affect the shape of a histogram. The Astropy docs have a great section on how to select these parameters: http://docs.astropy.org/en/stable/visualization/histogram.html · import matplotlib.pyplot as plt import numpy as np np.random.seed(19680801) n_bins = 10 x = np.random.randn(1000, 3) fig, ((ax0, ax1), (ax2, ax3)) = plt.subplots(nrows=2, ncols=2) colors = ['red', 'tan', 'lime'] ax0.hist(x, n_bins, density=True, histtype='ba
Find elsewhere
🌐
Nickmccullum
nickmccullum.com › python-visualization › histogram
How To Create Histograms in Python Using Matplotlib | Nick McCullum
An example is helpful. Below, you can see two histograms. The histogram on the left has 50 bins and the histogram on the right has 10 bins. In the next section, you'll learn how to create histograms in Python using matplotlib.
🌐
Analytics Vidhya
analyticsvidhya.com › home › matplotlib.pyplot.hist() in python: guide to plotting histograms
Matplotlib.pyplot.hist() in Python: Guide to Plotting Histograms - Analytics Vidhya
February 8, 2024 - The basic syntax of the Matplotlib.pyplot.hist() function is as follows: ... `bins`: This parameter specifies the number of bins to use in the histogram.
🌐
Real Python
realpython.com › python-histograms
Python Histogram Plotting: NumPy, Matplotlib, pandas & Seaborn – Real Python
March 18, 2026 - Moving on from the “frequency table” above, a true histogram first “bins” the range of values and then counts the number of values that fall into each bin. This is what NumPy’s histogram() function does, and it is the basis for other functions you’ll see here later in Python libraries such as Matplotlib and pandas.
🌐
Medium
la60312.medium.com › histogram-by-matplotlib-8764d2dab86c
Matplotlib Histogram with numbers on the top | by Tzung-Chien Hsieh | Medium
October 8, 2021 - Then we create a figure as usual by plt.subplot() and plot the histogram. For the number we want to put on the top of each bar, we need to get the position of each bar. So we use the bins return from ax.hist() to get the position on the x-axis. The position of the y-axis is the count which we already have. In the end, we use ax.text() to add the number on the top of each bar. The offset on the x and y-axis could be adjusted according to the bin size. By the example above, we will have a histogram like the one shown below.
🌐
Matplotlib
matplotlib.org › stable › gallery › statistics › histogram_histtypes.html
Demo of the histogram function's different histtype settings — Matplotlib 3.11.2 documentation
Go to the end to download the full example code. Histogram with step curve that has a color fill. Histogram with step curve with no fill. Histogram with custom and unequal bin widths. Two histograms with stacked bars. Selecting different bin counts and sizes can significantly affect the shape of a histogram. The Astropy docs have a great section on how to select these parameters: http://docs.astropy.org/en/stable/visualization/histogram.html · import matplotlib.pyplot as plt import numpy as np np.random.seed(19680801) mu_x = 200 sigma_x = 25 x = np.random.normal(mu_x, sigma_x, size=100) mu_w
🌐
CodingNomads
codingnomads.com › histograms-with-pandas-seaborn-and-matplotlib
Create Histograms with Pandas, Seaborn & Matplotlib
This allows you to add further customizations to any plot you make with pandas or seaborn using matplotlib.pyplot. ... Here you added the title "histogram" to the plot using the ax.set_title() method. Note, you can do this directly with pandas keyword title= but this is just an example of how you can use matplotlib.pyplot to add further customizations to your plot.
🌐
DataCamp
campus.datacamp.com › courses › intermediate-python › matplotlib
Basic plots with Matplotlib | Python
There are many visualization packages in python, but the mother of them all, is matplotlib. You will need its subpackage pyplot. By convention, this subpackage is imported as plt, like this. For our first example, let's try to gain some insights in the evolution of the world population.
🌐
StrataScratch
stratascratch.com › blog › how-to-create-a-matplotlib-histogram
How to Create a Matplotlib Histogram? - StrataScratch
March 10, 2025 - Normalized histograms are created easily in Matplotlib: set the density parameter to True in hist(). Here’s an example. I took the first two datasets from this StackOverflow question and created a .csv file with the same data.
🌐
LinkedIn
linkedin.com › pulse › how-plot-histogram-matplotlib-mohamed-riyaz-khan-vft7c
How to Plot a Histogram with Matplotlib
Login to LinkedIn to keep in touch with people you know, share ideas, and build your career.
🌐
DevGenius
blog.devgenius.io › creating-histograms-in-matplotlib-b77fd8135486
Creating Histograms in Matplotlib | by Someone | Dev Genius
October 4, 2024 - import matplotlib.pyplot as plt import numpy as np data = [1, 2, 2, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 7, 7, 7, 7, 7, 7, 7] plt.hist(data, bins=7) plt.savefig("Plots/fig_with_histogram.png") plt.clf() data = np.random.randn(1000) plt.hist(data, bins=30, color='green', edgecolor='black', density=True, cumulative=True) plt.savefig("Plots/fig_with_histogram_color.png") plt.clf() Two different histogram examples will be demonstrated: one with a simple frequency count and another with more advanced customizations like color, edgecolor, and cumulative distribution.
🌐
Canard Analytics
canardanalytics.com › blog › histogram-matplotlib
Plotting Histograms with Matplotlib | Canard Analytics
August 10, 2022 - Matplotlib has a powerful histogram functionality built into the package which is accessed through the matplotlib.pyplot.hist function. We'll work through two examples in this tutorial, showing first how to create a simple histogram by plotting the distribution of average male height around the World, and then how to add two histograms to a single plot by adding the average female height to our first plot.
🌐
TutorialsPoint
tutorialspoint.com › matplotlib › matplotlib_histogram.htm
Matplotlib - Histogram
In the following example, we are visualizing random data as a histogram with 30 bins, displaying it in green with a black edge. We are using the density=True parameter to represent the probability density − · import matplotlib.pyplot as plt ...
🌐
Pythonspot
pythonspot.com › home › matplotlib › python matplotlib histogram
Python Matplotlib Histogram — Tutorial with Examples
January 1, 2026 - # add a 'best fit' line y = mlab.normpdf(bins, mu, sigma) plt.plot(bins, y, 'r--') plt.xlabel('Smarts') plt.ylabel('Probability') plt.title(r'Histogram of IQ: $\mu=100$, $\sigma=15$') # Tweak spacing to prevent clipping of ylabel plt.subplots_adjust(left=0.15) plt.show() Output: ... Practice Plot exercises with the result next to yours You learn Matplotlib fastest by changing one line and looking at what moves.