Heatmaps (2024)

How to make Heatmaps in Python with Plotly.


New to Plotly?

Plotly is a free and open-source graphing library for Python. We recommend you read our Getting Started guide for the latest installation or upgrade instructions, then move on to our Plotly Fundamentals tutorials or dive straight in to some Basic Charts tutorials.

The term "heatmap" usually refers to a Cartesian plot with data visualized as colored rectangular tiles, which is the subject of this page. It is also sometimes used to refer to actual maps with density data displayed as color intensity.

Plotly supports two different types of colored-tile heatmaps:

  1. Matrix Heatmaps accept a 2-dimensional matrix or array of data and visualizes it directly. This type of heatmap is the subject of this page.
  2. Density Heatmaps accept data as a list and visualizes aggregated quantities like counts or sums of this data. Please refer to the 2D Histogram documentation for this kind of figure.

Heatmaps with Plotly Express

Plotly Express is the easy-to-use, high-level interface to Plotly, which operates on a variety of types of data and produces easy-to-style figures. With px.imshow, each value of the input array or data frame is represented as a heatmap pixel.

The px.imshow() function can be used to display heatmaps (as well as full-color images, as its name suggests). It accepts both array-like objects like lists of lists and numpy or xarray arrays, as well as pandas.DataFrame objects.

For more examples using px.imshow, including examples of faceting and animations, as well as full-color image display, see the the imshow documentation page.

In[1]:

import plotly.express as pxfig = px.imshow([[1, 20, 30], [20, 1, 60], [30, 60, 1]])fig.show()

In[2]:

import plotly.express as pxdf = px.data.medals_wide(indexed=True)fig = px.imshow(df)fig.show()

Displaying Text on Heatmaps

New in v5.5

You can add the values to the figure as text using the text_auto argument. Setting it to True will display the values on the bars, and setting it to a d3-format formatting string will control the output format.

In[3]:

import plotly.express as pxz = [[.1, .3, .5, .7, .9], [1, .8, .6, .4, .2], [.2, 0, .5, .7, .9], [.9, .8, .4, .2, 0], [.3, .4, .5, .7, 1]]fig = px.imshow(z, text_auto=True)fig.show()

Heatmaps in Dash

Dash is the best way to build analytical apps in Python using Plotly figures. To run the app below, run pip install dash, click "Download" to get the code and run python app.py.

Get started with the official Dash docs and learn how to effortlessly style & deploy apps like this with Dash Enterprise.

Out[4]:

Sign up for Dash Club → Free cheat sheets plus updates from Chris Parmer and Adam Schroeder delivered to your inbox every two months. Includes tips and tricks, community apps, and deep dives into the Dash architecture.Join now.

Controlling Aspect Ratio

By default, px.imshow() produces heatmaps with square tiles, but setting the aspect argument to "auto" will instead fill the plotting area with the heatmap, using non-square tiles.

In[5]:

import plotly.express as pxz = [[.1, .3, .5, .7, .9], [1, .8, .6, .4, .2], [.2, 0, .5, .7, .9], [.9, .8, .4, .2, 0], [.3, .4, .5, .7, 1]]fig = px.imshow(z, text_auto=True, aspect="auto")fig.show()

Customizing the axes and labels on a heatmap

You can use the x, y and labels arguments to customize the display of a heatmap, and use .update_xaxes() to move the x axis tick labels to the top:

In[6]:

import plotly.express as pxdata=[[1, 25, 30, 50, 1], [20, 1, 60, 80, 30], [30, 60, 1, 5, 20]]fig = px.imshow(data, labels=dict(x="Day of Week", y="Time of Day", color="Productivity"), x=['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday'], y=['Morning', 'Afternoon', 'Evening'] )fig.update_xaxes(side="top")fig.show()

Display an xarray image with px.imshow

xarrays are labeled arrays (with labeled axes and coordinates). If you pass an xarray image to px.imshow, its axes labels and coordinates will be used for axis titles. If you don't want this behavior, you can pass img.values which is a NumPy array if img is an xarray. Alternatively, you can override axis titles hover labels and colorbar title using the labels attribute, as above.

In[7]:

import plotly.express as pximport xarray as xr# Load xarray from dataset included in the xarray tutorialairtemps = xr.tutorial.open_dataset('air_temperature').air.sel(lon=250.0)fig = px.imshow(airtemps.T, color_continuous_scale='RdBu_r', origin='lower')fig.show()

Basic Heatmap with plotly.graph_objects

If Plotly Express does not provide a good starting point, it is also possible to use the more generic go.Heatmap class from plotly.graph_objects.

In[8]:

import plotly.graph_objects as gofig = go.Figure(data=go.Heatmap( z=[[1, 20, 30], [20, 1, 60], [30, 60, 1]]))fig.show()

Heatmap with Categorical Axis Labels

In this example we also show how to ignore hovertext when we have missing values in the data by setting the hoverongaps to False.

In[9]:

import plotly.graph_objects as gofig = go.Figure(data=go.Heatmap( z=[[1, None, 30, 50, 1], [20, 1, 60, 80, 30], [30, 60, 1, -10, 20]], x=['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday'], y=['Morning', 'Afternoon', 'Evening'], hoverongaps = False))fig.show()

Heatmap with Unequal Block Sizes

In[10]:

import plotly.graph_objects as goimport numpy as np# Build the rectangles as a heatmap# specify the edges of the heatmap squaresphi = (1 + np.sqrt(5) )/2. # golden ratioxe = [0, 1, 1+(1/(phi**4)), 1+(1/(phi**3)), phi]ye = [0, 1/(phi**3), 1/phi**3+1/phi**4, 1/(phi**2), 1]z = [ [13,3,3,5], [13,2,1,5], [13,10,11,12], [13,8,8,8] ]fig = go.Figure(data=go.Heatmap( x = np.sort(xe), y = np.sort(ye), z = z, type = 'heatmap', colorscale = 'Viridis'))# Add spiral line plotdef spiral(th): a = 1.120529 b = 0.306349 r = a*np.exp(-b*th) return (r*np.cos(th), r*np.sin(th))theta = np.linspace(-np.pi/13,4*np.pi,1000); # angle(x,y) = spiral(theta)fig.add_trace(go.Scatter(x= -x+x[0], y= y-y[0], line =dict(color='white',width=3)))axis_template = dict(range = [0,1.6], autorange = False, showgrid = False, zeroline = False, linecolor = 'black', showticklabels = False, ticks = '' )fig.update_layout(margin = dict(t=200,r=200,b=200,l=200), xaxis = axis_template, yaxis = axis_template, showlegend = False, width = 700, height = 700, autosize = False )fig.show()

Heatmap with Datetime Axis

In[11]:

import plotly.graph_objects as goimport datetimeimport numpy as npnp.random.seed(1)programmers = ['Alex','Nicole','Sara','Etienne','Chelsea','Jody','Marianne']base = datetime.datetime.today()dates = base - np.arange(180) * datetime.timedelta(days=1)z = np.random.poisson(size=(len(programmers), len(dates)))fig = go.Figure(data=go.Heatmap( z=z, x=dates, y=programmers, colorscale='Viridis'))fig.update_layout( title='GitHub commits per day', xaxis_nticks=36)fig.show()

Text on Heatmap Points

In this example we add text to heatmap points using texttemplate. We use the values from the text attribute for the text. We also adjust the font size using textfont.

In[12]:

import plotly.graph_objects as gofig = go.Figure(data=go.Heatmap( z=[[1, 20, 30], [20, 1, 60], [30, 60, 1]], text=[['one', 'twenty', 'thirty'], ['twenty', 'one', 'sixty'], ['thirty', 'sixty', 'one']], texttemplate="%{text}", textfont={"size":20}))fig.show()

Heatmap and datashader

Arrays of rasterized values build by datashader can be visualized usingplotly's heatmaps, as shown in the plotly and datashader tutorial.

Reference

See function reference for px.(imshow) or https://plotly.com/python/reference/heatmap/ for more information and chart attribute options!

What About Dash?

Dash is an open-source framework for building analytical applications, with no Javascript required, and it is tightly integrated with the Plotly graphing library.

Learn about how to install Dash at https://dash.plot.ly/installation.

Everywhere in this page that you see fig.show(), you can display the same figure in a Dash application by passing it to the figure argument of the Graph component from the built-in dash_core_components package like this:

import plotly.graph_objects as go # or plotly.express as pxfig = go.Figure() # or any Plotly Express function e.g. px.bar(...)# fig.add_trace( ... )# fig.update_layout( ... )from dash import Dash, dcc, htmlapp = Dash()app.layout = html.Div([ dcc.Graph(figure=fig)])app.run_server(debug=True, use_reloader=False) # Turn off reloader if inside Jupyter
Heatmaps (2)
Heatmaps (2024)
Top Articles
Convert US Dollar to Solana (USD to SOL) - BeInCrypto
Shipping terms explained: CFR, CIF, and FOB
Television Archive News Search Service
Stretchmark Camouflage Highland Park
Faridpur Govt. Girls' High School, Faridpur Test Examination—2023; English : Paper II
Craigslist Mpls Mn Apartments
Free Atm For Emerald Card Near Me
South Park Season 26 Kisscartoon
Mama's Kitchen Waynesboro Tennessee
DENVER Überwachungskamera IOC-221, IP, WLAN, außen | 580950
San Diego Terminal 2 Parking Promo Code
Owatc Canvas
More Apt To Complain Crossword
Heska Ulite
Best Private Elementary Schools In Virginia
Best Pawn Shops Near Me
Select Truck Greensboro
Pro Groom Prices – The Pet Centre
Colorado mayor, police respond to Trump's claims that Venezuelan gang is 'taking over'
2016 Hyundai Sonata Refrigerant Capacity
Razor Edge Gotti Pitbull Price
Canvas Nthurston
Craighead County Sheriff's Department
Illinois VIN Check and Lookup
Testberichte zu E-Bikes & Fahrrädern von PROPHETE.
Craigslist Pearl Ms
Rimworld Prison Break
Knock At The Cabin Showtimes Near Alamo Drafthouse Raleigh
Greenville Sc Greyhound
Yugen Manga Jinx Cap 19
Ontdek Pearson support voor digitaal testen en scoren
Disputes over ESPN, Disney and DirecTV go to the heart of TV's existential problems
eugene bicycles - craigslist
JVID Rina sauce set1
WPoS's Content - Page 34
Mchoul Funeral Home Of Fishkill Inc. Services
*!Good Night (2024) 𝙵ull𝙼ovie Downl𝚘ad Fr𝚎e 1080𝚙, 720𝚙, 480𝚙 H𝙳 HI𝙽DI Dub𝚋ed Fil𝙼yz𝚒lla Isaidub
Transformers Movie Wiki
Stolen Touches Neva Altaj Read Online Free
Quality Tire Denver City Texas
CARLY Thank You Notes
Craigslist Greencastle
Top 25 E-Commerce Companies Using FedEx
What Is A K 56 Pink Pill?
Actor and beloved baritone James Earl Jones dies at 93
Directions To Cvs Pharmacy
Gamestop Store Manager Pay
Goats For Sale On Craigslist
Darkglass Electronics The Exponent 500 Test
Epower Raley's
Latest Posts
Article information

Author: Prof. Nancy Dach

Last Updated:

Views: 6643

Rating: 4.7 / 5 (77 voted)

Reviews: 84% of readers found this page helpful

Author information

Name: Prof. Nancy Dach

Birthday: 1993-08-23

Address: 569 Waelchi Ports, South Blainebury, LA 11589

Phone: +9958996486049

Job: Sales Manager

Hobby: Web surfing, Scuba diving, Mountaineering, Writing, Sailing, Dance, Blacksmithing

Introduction: My name is Prof. Nancy Dach, I am a lively, joyous, courageous, lovely, tender, charming, open person who loves writing and wants to share my knowledge and understanding with you.