Show Sidebar Hide Sidebar

Heatmaps in matplotlib

How to make a heatmap in matplotlib with a matrix. Examples of colored and labeled heatmaps with custom colorscales.

New to Plotly?

Plotly's Python library is free and open source! Get started by downloading the client and reading the primer.
You can set up Plotly to work in online or offline mode, or in jupyter notebooks.
We also have a quick-reference cheatsheet (new!) to help you get started!

Version Check

Plotly's python package is updated frequently. Run pip install plotly --upgrade to use the latest version.

In [1]:
import plotly
plotly.__version__
Out[1]:
'3.1.1'

Basic Heatmap

In [2]:
import plotly.plotly as py
import plotly.tools as tls

import matplotlib.pyplot as plt
import numpy as np

fig = plt.figure()
ax = fig.add_subplot(111)

ax.set_title('Simple Heatmap with matplotlib and plotly')

plotly_fig = tls.mpl_to_plotly( fig )

trace = dict(z=[[1,20,30],[20,1,60],[30,60,1]], type="heatmap", zmin=1, zmax=60)

plotly_fig.add_traces([trace])

plotly_fig['layout']['xaxis'].update({'autorange':True})
plotly_fig['layout']['yaxis'].update({'autorange':True})

py.iplot(plotly_fig, filename='mpl-basic-heatmap')
Out[2]:

Heatmap With Custom Colorscale

In [3]:
import plotly.plotly as py
import plotly.tools as tls

import matplotlib.pyplot as plt
import numpy as np

fig = plt.figure()
ax = fig.add_subplot(111)

ax.set_title('Heatmap with Custom Colorscale (Viridis) ')

plotly_fig = tls.mpl_to_plotly( fig )

trace = dict(z=[[1,20,30],[20,1,60],[30,60,1]], type="heatmap", zmin=1, zmax=60, colorscale='Viridis')
plotly_fig.add_traces([trace])

plotly_fig['layout']['xaxis'].update({'autorange':True})
plotly_fig['layout']['yaxis'].update({'autorange':True})

py.iplot(plotly_fig, filename='mpl-heatmap-custom-colorscale')
Out[3]:

Reference

See https://plot.ly/python/reference/#heatmap for more information and chart attribute options!

Still need help?
Contact Us

For guaranteed 24 hour response turnarounds, upgrade to a Developer Support Plan.