Drawing A 2-D Heatmap In Python Using Matplotlib

Drawing A 2-D Heatmap In Python Using Matplotlib

Overview

A 2-D Heatmap is a tool used in data visualization for representing the magnitude of a phenomenon through colors. The “matplotlib” package in Python can be used to plot a 2-D heatmap. That’s exactly what we’re going to learn about in this article.

Scope

In this article you shall learn about the:

  • Using matplotlib.pyplot.imshow() method.
  • Using the Seaborn Library.
  • Using matplotlib.pyplot.pcolormesh() method.

Using matplotlib.pyplot.imshow() method

Syntax

matplotlib.pyplot.imshow(X, cmap=None, norm=None,
aspect=None, interpolation=None, alpha=None, vmin=None,
vmax=None, origin=None, extent=None, shape=<deprecated
parameter>, filternorm=1, filterrad=4.0, imlim=<deprecated
parameter>, resample=None, url=None, \*, data=None,
\*\*kwargs)

Example

import numpy as numpy
import matplotlib.pyplot as mplpt
data = numpy.random.random(( 30, 30))
mplpt.imshow( data , cmap = 'autumn' , interpolation = 'nearest' )
mplpt.title( "2-D Heat Map" )
mplpt.show()

Output

write your code here: Coding Playground

Using Seaborn Library

Syntax

seaborn.heatmap(data, *, vmin=None, vmax=None, cmap=None,
center=None, robust=False,annot=None, fmt='.2g',
annot_kws=None, linewidths=0, linecolor='white', cbar=True,
cbar_kws=None, cbar_ax=None, square=False,
xticklabels='auto', yticklabels='auto', mask=None, ax=None,
**kwargs)

Example

import numpy as numpy
import seaborn as seaborn
import matplotlib.pylab as mplpl
dataSet = numpy.random.rand( 10 , 10 )
ax = seaborn.heatmap( dataSet , linewidth = 0.5 , cmap = 'coolwarm' )
mplpl.title( "A 2-D Heatmap" )
mplpl.show()

Output

write your code here: Coding Playground

Using matplotlib.pyplot.pcolormesh() method

Syntax

matplotlib.pyplot.pcolormesh(*args, alpha=None, norm=None,
cmap=None, vmin=None, vmax=None, shading='flat',
antialiased=False, data=None, **kwargs)

Example

import matplotlib.pyplot as mplpp
import numpy as numpy
Z = numpy.random.rand( 23 , 23)
mplpp.pcolormesh( Z , cmap = 'summer'
mplpp.title( 'A 2-D Heatmap' )
mplpp.show()

Output

write your code here: Coding Playground