GeezerVison is showing plotly.com — Heatmaps in Python
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:
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.
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.
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 supported 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.
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.
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.
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.
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.
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]:
importplotly.expressaspxdata=[[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()
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]:
importplotly.expressaspximportxarrayasxr# 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()
importplotly.graph_objectsasgoimportnumpyasnp# 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 plotdefspiral(th):a=1.120529b=0.306349r=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()
importplotly.graph_objectsasgoimportdatetimeimportnumpyasnpnp.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=dict(text='GitHub commits per day'),xaxis_nticks=36)fig.show()
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.
Dash is an open-source framework for building analytical applications, with no Javascript required, and it is tightly integrated with the Plotly graphing library.
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:
importplotly.graph_objectsasgo# or plotly.express as pxfig=go.Figure()# or any Plotly Express function e.g. px.bar(...)# fig.add_trace( ... )# fig.update_layout( ... )fromdashimportDash,dcc,htmlapp=Dash()app.layout=html.Div([dcc.Graph(figure=fig)])app.run(debug=True,use_reloader=False)# Turn off reloader if inside Jupyter
You are visitor 01402503 — GeezerVison does not store the pages you look up. Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.