Plotting heat map in python

How to Create Heatmaps in Python?

In this tutorial, we will look at how to create heatmaps in Python with the help of some examples.

What are Heatmaps?

Heatmaps use colour changes like hue, saturation, or brightness to depict the data as 2-D coloured maps. Instead of using numbers to represent relationships between variables, heatmaps use colours.

📚 Discover Online Data Science Courses & Programs (Enroll for Free)

Introductory ⭐

Intermediate ⭐⭐⭐

🔎 Find Data Science Programs 👨‍💻 111,889 already enrolled

Disclaimer: Data Science Parichay is reader supported. When you purchase a course through a link on this site, we may earn a small commission at no additional cost to you. Earned commissions help support this website and its team of writers.

On both axes, these variables are plotted. The intensity of the colour in a given block determines the relationship between two values, and this relationship is described by the colour changes.

We can plot Heatmaps in different ways, they are:

  1. Using the seaborn library’s heatmap() method.
  2. Using the matplotlib.pyplot.pcolormesh() method.
  3. Using the matplotlib.pyplot.imshow() method.

Let’s now look at the above methods in detail.

Heatmap the seaborn.heatmap() method

In this method, we are going to use seaborn.heatmap() function to create a heatmap. The following is the syntax –

Basic 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)

data: 2D dataset that can be coerced into an ndarray. If a Pandas DataFrame is provided, the index/column information will be used to label the columns and rows.

For more details, about the parameter, refer this.

Now, let us understand the above method, with some examples.

Example 1 – Simple heatmap

# Import Modules import numpy as np import seaborn as sns # Generate a 10x10 random integer matrix data = np.random.rand(10,10) # Plot the heatmap sns.heatmap(data)

the resulting heatmap plot

The steps followed in the above example are:

  • import the required modules
  • generate a 10*10 grid with random values
  • plot a heatmap using seaborn.heatmap method.

Example 2 – Heatmap with customizations

You can further customize the heatmap with additional arguments to the seaborn.heatmap() function. For example, let’s increase the line width in the heatmap and add annotations.

# 1. Import Modules import numpy as np import seaborn as sns # 2. Generate a 10x10 random integer matrix data = np.random.rand(10,10) # 3. Plot the heatmap sns.heatmap(data, linewidth = 1, annot=True)

the resulting heatmap with customizations

The steps followed in the above example are:

  • import the required modules
  • generate a 10*10 grid with random values
  • plot a heatmap using seaborn.heatmap method along with customizations.

Heatmap using the matplotlib.pyplot.pcolormesh() method

In this method, we use the matplotlib.pyplot.pcolormesh function to create a heatmap. The following is the syntax –

Basic Syntax:

matplotlib.pyplot.pcolormesh([X, Y,] C, **kwargs)
  • C: The color-mapped values. Color-mapping is controlled by cmap, norm, vmin, and vmax.
  • X, Y: The coordinates of the corners of quadrilaterals of a pcolormesh

For more details, about the parameters, refer this.

Now let us try to understand the above method with some examples.

Example 1 – Simple heatmap

Let’s draw the same heatmap as above (heatmap of a random 10×10 grid of values).

import matplotlib.pyplot as plt import numpy as np #Generate a 10x10 random integer matrix data= np.random.rand(10,10) #plotting the heatmap plt.pcolormesh(data) plt.show()

the resulting heatmap plot

The steps followed in the above example are:

  • import the required modules
  • generate a 10*10 grid with random values
  • plot a heatmap using pyplot.pcolormesh method.

Example 2 – Heatmap with customizations

You can further customize the heatmap with additional arguments to the matplotlib.pyplot.pcolormesh() function. For example, we could change the color map using the cmap parameter.

Let’s plot the same heatmap of different subplots with different cmap values.

import matplotlib.pyplot as plt import numpy as np #Generate a 10x10 random integer matrix data= np.random.rand(10,10) #plotting the heatmap plt.subplot(2,2,1) plt.pcolormesh(data, cmap = 'rainbow') #plotting the heatmap plt.subplot(2,2,2) p1 =plt.pcolormesh(data, cmap = 'twilight') #plotting the heatmap plt.subplot(2,2,3) plt.pcolormesh(data, cmap = 'summer') #plotting the heatmap plt.subplot(2,2,4) plt.pcolormesh(data, cmap = 'winter') plt.tight_layout() plt.show()

subplots with heatmaps with different cmaps

The steps followed in the above example are:

  • import the required modules
  • generate a 10*10 grid with random values
  • plot a heatmap using pyplot.pcolormesh method in different subplots.

To know more about the cmap argument, refer this.

Heatmap using the matplotlib.pyplot.imshow() method

In this method, we use matplotlib.pyplot.imshow method to create a heatmap. The imshow() method is used to display data as an image. The following is the syntax –

Basic Syntax:

matplotlib.pyplot.imshow(X, cmap=None, norm=None, *, aspect=None, interpolation=None, alpha=None, vmin=None, vmax=None, origin=None, extent=None, interpolation_stage=None, filternorm=True, filterrad=4.0, resample=None, url=None, data=None, **kwargs)

    X: The image data. Supported array shapes are:

(M, N): an image with scalar data. The values are mapped to colors using normalization and a colormap. See parameters norm, cmap, vmin, vmax.
(M, N, 3): an image with RGB values (0-1 float or 0-255 int).
(M, N, 4): an image with RGBA values (0-1 float or 0-255 int), i.e. including transparency.
The first two dimensions (M, N) define the rows and columns of the image.

For more details, about the parameters, refer this.

Now let us understand the above method using some examples.

Example 1 – Simple heatmap

Let’s draw the same heatmap for the data used in the above methods (a random 10×10 grid of values) using the maplotlib.pyplot.imshow() method.

import numpy as np import matplotlib.pyplot as plt #Generate a 10x10 random integer matrix data= np.random.random((10,10)) #plotting the heatmap plt.imshow( data, interpolation = 'nearest',cmap="twilight") plt.show()

the resulting heatmap

The steps followed in the above example are:

  • import the required modules
  • generate a 10*10 grid with random values
  • plot a heatmap using plt.imshow method.

Example 2 – Heatmap with customizations

We can also further customize the heatmap with additional arguments to the matpltolib.pyplot.imshow() function. For example, let’s change the colormap in the above heatmap and draw different heatmaps on subplots with different colormaps.

import numpy as np import matplotlib.pyplot as plt #Generate a 10x10 random integer matrix data= np.random.random((10,10)) #plotting the heatmap plt.subplot(2,2,1) plt.imshow( data, interpolation = 'nearest',cmap="rainbow") plt.subplot(2,2,2) plt.imshow( data, interpolation = 'nearest',cmap="twilight") plt.subplot(2,2,3) plt.imshow( data, interpolation = 'nearest',cmap="summer") plt.subplot(2,2,4) plt.imshow( data, interpolation = 'nearest',cmap="ocean") plt.tight_layout() plt.show()

subplots with heatmaps having different cmaps

The steps followed in the above example are:

  • import the required modules
  • generate a 10*10 grid with random values
  • plot a heatmap using pyplot.imshow method in different subplots.

To know more about the cmap argument, refer this.

You might also be interested in –

Subscribe to our newsletter for more informative guides and tutorials.
We do not spam and you can opt out any time.

Author

I’m an undergrad student at IIT Madras interested in exploring new technologies. I have worked on various projects related to Data science, Machine learning & Neural Networks, including image classification using Convolutional Neural Networks, Stock prediction using Recurrent Neural Networks, and many more machine learning model training. I write blog articles in which I would try to provide a complete guide on a particular topic and try to cover as many different examples as possible with all the edge cases to understand the topic better and have a complete glance over the topic. View all posts

Data Science Parichay is an educational website offering easy-to-understand tutorials on topics in Data Science with the help of clear and fun examples.

Источник

seaborn.heatmap#

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 ) #

Plot rectangular data as a color-encoded matrix.

This is an Axes-level function and will draw the heatmap into the currently-active Axes if none is provided to the ax argument. Part of this Axes space will be taken and used to plot a colormap, unless cbar is False or a separate Axes is provided to cbar_ax .

Parameters : data rectangular dataset

2D dataset that can be coerced into an ndarray. If a Pandas DataFrame is provided, the index/column information will be used to label the columns and rows.

vmin, vmax floats, optional

Values to anchor the colormap, otherwise they are inferred from the data and other keyword arguments.

cmap matplotlib colormap name or object, or list of colors, optional

The mapping from data values to color space. If not provided, the default will depend on whether center is set.

center float, optional

The value at which to center the colormap when plotting divergent data. Using this parameter will change the default cmap if none is specified.

robust bool, optional

If True and vmin or vmax are absent, the colormap range is computed with robust quantiles instead of the extreme values.

annot bool or rectangular dataset, optional

If True, write the data value in each cell. If an array-like with the same shape as data , then use this to annotate the heatmap instead of the data. Note that DataFrames will match on position, not index.

fmt str, optional

String formatting code to use when adding annotations.

annot_kws dict of key, value mappings, optional

Keyword arguments for matplotlib.axes.Axes.text() when annot is True.

linewidths float, optional

Width of the lines that will divide each cell.

linecolor color, optional

Color of the lines that will divide each cell.

cbar bool, optional

Whether to draw a colorbar.

cbar_kws dict of key, value mappings, optional

cbar_ax matplotlib Axes, optional

Axes in which to draw the colorbar, otherwise take space from the main Axes.

square bool, optional

If True, set the Axes aspect to “equal” so each cell will be square-shaped.

xticklabels, yticklabels “auto”, bool, list-like, or int, optional

If True, plot the column names of the dataframe. If False, don’t plot the column names. If list-like, plot these alternate labels as the xticklabels. If an integer, use the column names but plot only every n label. If “auto”, try to densely plot non-overlapping labels.

mask bool array or DataFrame, optional

If passed, data will not be shown in cells where mask is True. Cells with missing values are automatically masked.

ax matplotlib Axes, optional

Axes in which to draw the plot, otherwise use the currently-active Axes.

kwargs other keyword arguments

All other keyword arguments are passed to matplotlib.axes.Axes.pcolormesh() .

Returns : ax matplotlib Axes

Axes object with the heatmap.

Plot a matrix using hierarchical clustering to arrange the rows and columns.

Pass a DataFrame to plot with indices as row/column labels:

glue = sns.load_dataset("glue").pivot("Model", "Task", "Score") sns.heatmap(glue) 
/var/folders/qk/cdrdfhfn5g554pnb30pp4ylr0000gn/T/ipykernel_77613/2862412127.py:1: FutureWarning: In a future version of pandas all arguments of DataFrame.pivot will be keyword-only. glue = sns.load_dataset("glue").pivot("Model", "Task", "Score") 

../_images/heatmap_1_1.png

Use annot to represent the cell values with text:

../_images/heatmap_3_0.png

Control the annotations with a formatting string:

sns.heatmap(glue, annot=True, fmt=".1f") 

../_images/heatmap_5_0.png

Use a separate dataframe for the annotations:

sns.heatmap(glue, annot=glue.rank(axis="columns")) 

../_images/heatmap_7_0.png

sns.heatmap(glue, annot=True, linewidth=.5) 

../_images/heatmap_9_0.png

Select a different colormap by name:

../_images/heatmap_11_0.png

Or pass a colormap object:

sns.heatmap(glue, cmap=sns.cubehelix_palette(as_cmap=True)) 

../_images/heatmap_13_0.png

Set the colormap norm (data values corresponding to minimum and maximum points):

sns.heatmap(glue, vmin=50, vmax=100) 

../_images/heatmap_15_0.png

Use methods on the matplotlib.axes.Axes object to tweak the plot:

ax = sns.heatmap(glue, annot=True) ax.set(xlabel="", ylabel="") ax.xaxis.tick_top() 

Источник

Читайте также:  Python pip install transformers
Оцените статью