×

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 List reverse() method

 Python List reverse() method The list.reverse () method in Python reverses the elements of the list in place. Syntax list.reverse() Parameter NA Example 1 # Python program explaining # the list.reverse() method weekList = ['Sun','Thurs','Mon','Fri', 'Tues', 'Wed'] print("Actual week list: ",weekList) #...

1 minute read.

Image to Text in python

Processing out information from an image is a very big task in all the fields of work such as in development and business sector. The process of converting an electronical...

3 minutes read.

Writing to a CSV file in Python

Python is an Object-Oriented high-level language. Python has an English-like syntax, which is very easy to read and write codes. Python is an interpreted language which means that it uses...

6 minutes read.

Number Pattern Programs in Python

Learning Python is very easy, and it understands in better way compared to other programming languages. One of the many reasons why it has emerged as the most widely used...

4 minutes read.

List Assignment Index out of Range in Python

As we know, a List is one of the four unique data structures available in Python; In this tutorial, we will deep dive into understanding iterating through a list and...

3 minutes read.

How To Compare Two Strings In Python

In this article, we will discuss how to compare two strings in Python. So, before that, let’s have a quick revision on “What are strings?” Strings are a sequence of characters that...

5 minutes read.

Python OOPs: Class, Object, Inheritance and Constructor

Basic Object-Oriented Programming (OOP) Concepts in Python Python is similar to most general-purpose programming languages with an Object-Oriented environment system since its existence. Being an Object-Oriented Programming language, Python provides ease...

9 minutes read.

Working with CSV files in Python

Python is an Object-Oriented high-level language. Python has an English-like syntax, which is very easy to read and write codes. Python is an interpreted language which means that it uses...

7 minutes read.

Python Program to Find the gcd of Two Numbers

Introduction Greatest Common Divisor is the full form of gcd. The greatest common divisor, or GCD, of two numbers, is a value that can exactly divide the two digits and is...

5 minutes read.

Accessing Key-value in Dictionary in Python

A Python word reference is an assortment of key-esteem matches where each key is related to worth. Worth in the key-esteem pair can be a number, a string, a rundown,...

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.

Polymorphism in Python

What is polymorphism and why is it important? Polymorphism's literal definition is the state of occurring in diverse shapes or forms. When it comes to programming, the idea of polymorphism is crucial....

3 minutes read.

Python Set issubset() method

Python Set issubset() method The set.issubset() method in Python returns True if all items in the set exists in the specified set, otherwise it returns False. Syntax set.issubset(set1) Parameter set- This parameter represents the set to check whether...

2 minutes read.

Python input() function

Python input() function The input() function in Python reads a line from input and converts it to a string (stripping a trailing newline). Syntax input([prompt]) Parameter prompt: This function represents a string, depicting a default...

1 minute read.

Python Combination

Python Combination Permutations and combinations are the important part of our mathematical tools. We use them often in our Python programs. In this tutorial, we will learn about combinations in Python...

6 minutes read.

How to convert Float to Int in Python?

A float value can be converted to an int via type conversion, an explicit method of transforming an operand to a certain type. But it must be noted that such...

3 minutes read.

How to Read html page in python

Html is a Hyper Text Markup language is a standard language used for creating webpages. HTML is the name of the language used to describe the construction of Web pages....

4 minutes read.

Python Logging Maxbytes

Python: Python is an interactive and more accessible language than any other programming language. The python programming language uses a variety of libraries to perform the operations in a faster way....

6 minutes read.

Check whether dir is empty or not in python

Python: Check if a directory is empty In this tutorial, we will study how to check whether the director (dir) is empty or not in the python programming language. First of...

3 minutes read.

Python Dictionary values() method

Python Dictionary values() method The dictionary.values() method in Python returns a view object that displays a list of all the values in the specified dictionary. Syntax dictionary.values() Parameter NA Return This method returns a view object. The...

1 minute read.