Plot 2-D Histogram in Python using Matplotlib

Python | 2-D Histogram: Here, we are going to learn and implement the Plot 2-D Histogram in Python using Matplotlib.
Submitted by Anuj Singh, on July 22, 2020

A 2D-histogram is a graphical technique or a type of data representation using squares of different color ratios such that each square group's numbers into ranges (bins or buckets). Higher the color ratio (as it is dependent on the type of cmap) higher the data fall in that bin. A Histogram is one of the most used techniques in data visualization and a 2D Histogram is a further extension. Therefore, matplotlib has provided a function matplotlib.pyplot.hist2d() for plotting 2D histograms.

The following example shows an illustration of the 2D-histogram.

Python | 2D Histogram (1)

Python | 2D Histogram (2)

Python | 2D Histogram (3)

Python | 2D Histogram (4)

Python implementation of plot 2-d histogram using matplotlib

import matplotlib.pyplot as plt
import numpy as np

#random data generation
mu, sigma = 100, 15
x = mu + sigma * np.random.randn(100)

mu_w = 200
sigma_w = 10
w = np.random.normal(mu_w, sigma_w, size=100)

#2D Histogram of the Data
plt.figure()
plt.hist2d(x,w,bins=10)
plt.title('barstacked')
plt.xlabel('x')
plt.ylabel('w')
plt.title('2D Histogram : Bins=10')
plt.show()

plt.figure()
plt.hist2d(x, w, bins=25)
plt.title('barstacked')
plt.xlabel('x')
plt.ylabel('w')
plt.title('2D Histogram : Bins=25')
plt.show()

plt.figure()
plt.hist2d(x, w, bins=10, cmap='coolwarm_r')
plt.title('barstacked')
plt.xlabel('x')
plt.ylabel('w')
plt.title('2D Histogram : Cmap with 10 Bins')
plt.show()

plt.figure()
plt.hist2d(x, w, bins=25, cmap='coolwarm_r')
plt.title('barstacked')
plt.xlabel('x')
plt.ylabel('w')
plt.title('2D Histogram : Cmap with 25 Bins')
plt.show()

Output:

Output is as figure





Comments and Discussions

Ad: Are you a blogger? Join our Blogging forum.





Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates


© https://www.includehelp.com some rights reserved.