×

How to plot a Histogram in Python

A Histogram is used to represent a given data provided as a chunk. This histogram is a graphical representation that uses bars to indicate the ranges of the data. In this data representation, the x-axis represents the main ranges, and the y-axis represents the information about the frequency. In this article, we shall learn about plotting this histogram in python.

In python, we generally use two main libraries of a data frame. We use these libraries for any graphical representation like a line graph, bar graph, pie chart, histogram, etc. They are matplotlib and seaborn. We get these libraries from Pandas data frame. Now let us learn a way to plot a histogram in python using the library matplotlib.

Creating Histogram

The primary thing before creating a histogram is to set up the ranges for the graph and then divide the complete range of the values into a sequential interval. Then we count the values, which are into intervals.

The main function command we use to create a histogram is “matplotlib. pyplot.hist()”

Now let us create a basic histogram and use a data set containing some random values. Let us follow the code below

Example

from matplotlib import pyplot as plt
import numpy as np
 
 
# Creating a random dataset
a = np.array([25, 89, 15, 48, 66,
              70, 59, 58, 31,
              20, 81, 51, 70, 31,
              26])
 
# Creating a histogram
fig, ax = plt.subplots(figsize =(5, 9))
ax.hist(a, bins = [0, 20, 40, 60, 80, 100])
 
# Show the plot
plt.show()

Output

How to plot a Histogram in Python

So, in the above code, we first imported pyplot from the library matplotlib. Next, we imported NumPy because we are dealing with numbers. And then, we created a random data set by naming it “a.” after creation. We created the histogram by fixing the subplots and then assigning the bin ranges for the graph. Finally, we give a plt.show() command to print the whole graph. After execution, we finally printed the plot.

Customization of Histogram

Matplotlib has a wide range of customizations for the histogram. The function matplotlib.pyplot.hist() has many built-in attributes which help modify a histogram. To access and change the created objects, the function hist() provides a patches object that will help change. With this function, we can customize the plot according to the requirements.

For example, let us look at this code

Example

import matplotlib.pyplot as plt
import numpy as np
from matplotlib import colors
from matplotlib.ticker import PercentFormatter
 
# Creating a random dataset
np.random.seed(23685765)
N_points = 1000
n_bins = 25
 
# Creating the required distribution
x = np.random.randn(N_points)
y = .8 ** x + np.random.randn(1000) + 25
 
# Creating a histogram
fig, axs = plt.subplots(1, 1,
                        figsize =(5, 7),
                        tight_layout = True)
 
axs.hist(x, bins = n_bins)
 
# Show the plot
plt.show()

Output:

How to plot a Histogram in Python

In the above code, we just created a random histogram, and now we will modify it according to our requirement, so let us look at the code continuation of this histogram.

Exqmple

import matplotlib.pyplot as plt
import numpy as np
from matplotlib import colors
from matplotlib.ticker import PercentFormatter
 
# Creating a random dataset
np.random.seed(23685765)
N_points = 1000
n_bins = 25
 
# Creating the required distribution
x = np.random.randn(N_points)
y = .8 ** x + np.random.randn(1000) + 25
 
# Creating a histogram
fig, axs = plt.subplots(1, 1,
                        figsize =(5, 7),
                        tight_layout = True)
 
# Removing the axes splines
for s in ['top', 'bottom', 'left', 'right']:
    axs.spines[s].set_visible(False)
 
# Removing the x, y ticks
axs.xaxis.set_ticks_position('none')
axs.yaxis.set_ticks_position('none')
   
# Add padding between the axes and the label
axs.xaxis.set_tick_params(pad = 10)
axs.yaxis.set_tick_params(pad = 15)
 
# Adding required x, y gridlines
axs.grid(b = True, color ='orange',
        linestyle ='-.', linewidth = 1,
        alpha = 0.5)
 
# Add Text watermark
fig.text(1, 0.25, 'new',
         fontsize = 10,
         color ='blue',
         ha ='right',
         va ='bottom',
         alpha = 0.8)
 
# Creating the customised histogram
N, bins, patches = axs.hist(x, bins = n_bins)
 
# Setting color
fracs = ((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 plot
plt.show()

Output:

How to plot a Histogram in Python

This code shows the changes we made from the previous histogram to this one. The only difference is the extra code we wrote after creating the histogram. So we first removed axes splines, then removed x and y ticks. Now we added padding between axes and labels and grid lines by setting their width. At the bottom of the graph, we also inserted a new watermark. And then, we added colors to the bars in the histogram. And finally, we print the histogram.

Conclusion

In this way, we can create a histogram in python and customize them according to our requirements.


Related Topics

Python AIOHTTP

Python 3.5 introduced some new syntax that makes it simpler for developers to make asynchronous programmes and packages. Aiohttp, an HTTP client/server for asyncio, is one such package. In essence,...

3 minutes read.

Difference Between Python and Scala

What is Python? Python is a high-level general-purpose interpreted programing language. It is used for multi general-purpose work such as language construct as well as its object-oriented approach aims to help...

4 minutes read.

Reverse a String in Python

Python is an object-oriented high-level programming language. Python has dynamic semantics and has high-level built-in data structures which support dynamic typing and dynamic binding. Python provides rapid development. It has...

4 minutes read.

Reading a File Line by Line in Python

Introduction In this tutorial, we will learn about reading files in python line by line. Before reading the files, let us know a little information about the files first. Files A file is...

6 minutes read.

Python open() function

Python open() function The open() function in Python opens a file and returns a corresponding file object. If the file cannot be opened, an OSError is raised. Syntax open(file, mode='r', buffering=1, encoding=None, errors=None, newline=None, closefd=True, opener=None) Parameter file It represents the path and name of the file mode...

2 minutes read.

Difference between Yield and Return in Python

Python yield statement The generators are defined by using the yield statement in Python. Generally, it converts a normal Python function into a generator.  The yield statement hauls the function and returns...

3 minutes read.

Python Infinity

Introduction We will discover how to define an infinite number in Python in this tutorial. Infinity, as we all know, is a value that cannot be defined and can either be...

5 minutes read.

Python List count() method

Python List count() method The list.count() method returns the number of times x appears in the list. Syntax list.count(x) Parameter x: This parameter represents the value to search for and can contain any iterable (list, set, tuple, etc.) Return This method returns the...

1 minute read.

Python Time Module

Python contains many files that can be imported into a python code and used whenever we want. One of that modules is the time module. It is a good practice...

6 minutes read.

Python String rjust() method

Python String rjust() method The string.rjust() method in Python returns a right-justified string of a given minimum width where the padding is done using the specified fillchar (default is a space). It returns...

2 minutes read.

Python Deep Copy and Shallow Copy

Assignment statements in Python create bindings between a target and an object, not copies of them. The = operator only makes a new variable that shares the reference to the...

3 minutes read.

Python whois

What is whois? Whois is a protocol used to identify the owner of the registered domain name. It is a querying database that is used to record the registered users. WHOIS is...

4 minutes read.

Exponentiation in Python

What is an Exponent in Python? Exponent is a fundamental mathematical concept that is used in many different areas, such as engineering, physics, and finance. In mathematics, an exponent is a...

4 minutes read.

Python MySQL Update Operation

Python MySQL Update Operation: In this part of tutorial, we will learn that how can we update a table present in SQL database through our Python program. As like SQL,...

4 minutes read.

Python Dictionary setdefault() method

Python Dictionary setdefault() method The dictionary.setdefault () method in Python returns the value of the item with the specified key. Syntax dictionary.setdefault(keyname, value) Parameter keyname- This parameter represents the keyname of the item you want...

1 minute read.

Returning Multiple Values in Python

Python is considered a general-purpose programming language; it is a high-level programming language that is not much difficult and easier to learn. It is rich in libraries that can be...

3 minutes read.

Index Error in Python

The index errors are the run time error that is raised in Python when we try to access an index that does not exist. This might seem very trivial but...

4 minutes read.

Python Examples

In this tutorial, we will see some examples related to python. This will include some basic example questions and their code in Python. Write a program to print “Hello Python”. print(‘Hello Python’) Output Hello...

5 minutes read.

Python Assert

Python Assert Python provides an assert statement which is used to check the logical expression. If the given logical expression is true, then it precedes for the next line; otherwise, it raises an...

2 minutes read.

How to create a dictionary in Python?

How to create a dictionary in python Dictionary is a data structure in Python that represents our data in the form of keys and values. Each value in a dictionary can be...

5 minutes read.