• This is a new feature in 5.5.0 https://github.com/plotly/plotly.py/releases. After installing and restarting my jupyter kernel, this did not work. Required restart of complete jupyter environment
  • the documented example using go https://plotly.com/python/heatmaps/#text-on-heatmap-points plus note in release notes auto_text parameter, I explored this.
  • below shows use of px and also go by adding numbers as text as well

import plotly.express as px
import plotly.graph_objects as go
import inflect

p = inflect.engine()
df = px.data.medals_wide(indexed=True)
fig = px.imshow(df, text_auto=True)
fig2 = go.Figure(fig.data, fig.layout)
fig2 = fig2.update_traces(text=df.applymap(p.number_to_words).values, texttemplate="%{text}", hovertemplate=None)

fig.show()
fig2.show()

dash

  • see https://dash.plotly.com/external-resources Controlling the Plotly.js Version Used by dcc.Graph
  • dash 2.0.0 is packaged with a version of plotly.js that does not yet support texttemplate
  • code below shows how to override
import numpy as np
import dash
import plotly.graph_objects as go
import plotly.express as px
from dash.dependencies import Input, Output, State
from jupyter_dash import JupyterDash
import inflect

# Build App
app = JupyterDash(__name__, external_scripts=["https://cdn.plot.ly/plotly-2.8.3.min.js"])
app.scripts.config.serve_locally = False
app.layout = dash.html.Div(
    [
        dash.dcc.Interval(id="run", max_intervals=1),
        dash.dcc.Graph(id="fig"),
    ]
)


def hm():
    p = inflect.engine()
    df = px.data.medals_wide(indexed=True)
    fig = px.imshow(df, text_auto=True)
    fig2 = go.Figure(fig.data, fig.layout)
    fig2 = fig2.update_traces(
        text=df.applymap(p.number_to_words).values,
        texttemplate="%{text}",
        hovertemplate=None,
    )
    return fig2.update_layout(title=f"dash: {dash.__version__}")


@app.callback(Output("fig", "figure"), Input("run", "n_intervals"))
def createFig(n):
    return hm()


# Run app and display result inline in the notebook
app.run_server(mode="inline")
Answer from Rob Raymond on Stack Overflow
🌐
Plotly
plotly.com › python › heatmaps
Heatmaps in Python
Alternatively, you can override axis titles hover labels and colorbar title using the labels attribute, as above. In [7]: import plotly.express as px import xarray as xr # Load xarray from dataset included in the xarray tutorial airtemps = 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() 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.
🌐
Plotly
plotly.github.io › plotly.py-docs › generated › plotly.graph_objects.Heatmap.html
plotly.graph_objects.Heatmap — 7.0.0 documentation
The ‘labelalias’ property accepts values of any type ... Sets the length of the color bar This measure excludes the padding of both ends. That is, the color bar length is this length minus the padding on both ends. The ‘len’ property is a number and may be specified as: ... Determines whether this color bar’s length (i.e. the measure in the color variation direction) is set in units of plot “fraction” or in *pixels.
Top answer
1 of 1
9
  • This is a new feature in 5.5.0 https://github.com/plotly/plotly.py/releases. After installing and restarting my jupyter kernel, this did not work. Required restart of complete jupyter environment
  • the documented example using go https://plotly.com/python/heatmaps/#text-on-heatmap-points plus note in release notes auto_text parameter, I explored this.
  • below shows use of px and also go by adding numbers as text as well

import plotly.express as px
import plotly.graph_objects as go
import inflect

p = inflect.engine()
df = px.data.medals_wide(indexed=True)
fig = px.imshow(df, text_auto=True)
fig2 = go.Figure(fig.data, fig.layout)
fig2 = fig2.update_traces(text=df.applymap(p.number_to_words).values, texttemplate="%{text}", hovertemplate=None)

fig.show()
fig2.show()

dash

  • see https://dash.plotly.com/external-resources Controlling the Plotly.js Version Used by dcc.Graph
  • dash 2.0.0 is packaged with a version of plotly.js that does not yet support texttemplate
  • code below shows how to override
import numpy as np
import dash
import plotly.graph_objects as go
import plotly.express as px
from dash.dependencies import Input, Output, State
from jupyter_dash import JupyterDash
import inflect

# Build App
app = JupyterDash(__name__, external_scripts=["https://cdn.plot.ly/plotly-2.8.3.min.js"])
app.scripts.config.serve_locally = False
app.layout = dash.html.Div(
    [
        dash.dcc.Interval(id="run", max_intervals=1),
        dash.dcc.Graph(id="fig"),
    ]
)


def hm():
    p = inflect.engine()
    df = px.data.medals_wide(indexed=True)
    fig = px.imshow(df, text_auto=True)
    fig2 = go.Figure(fig.data, fig.layout)
    fig2 = fig2.update_traces(
        text=df.applymap(p.number_to_words).values,
        texttemplate="%{text}",
        hovertemplate=None,
    )
    return fig2.update_layout(title=f"dash: {dash.__version__}")


@app.callback(Output("fig", "figure"), Input("run", "n_intervals"))
def createFig(n):
    return hm()


# Run app and display result inline in the notebook
app.run_server(mode="inline")
🌐
Snyk
snyk.io › advisor › plotly › functions › plotly.graph_objs.heatmap
How to use the plotly.graph_objs.Heatmap function in plotly | Snyk
# Creating the plotly figure, which is also a widget x = _ensure_string_from_expression(x) y = _ensure_string_from_expression(y) binby = [] for expression in [y, x]: if expression is not None: binby = [expression] + binby limits = self.df.limits(binby, limits) extent, counts = self._grid(expr=binby, what=what, shape=shape, limits=limits, f=_widget_f.v_model, n=n, selection=selection, progress=progress) cbar = go.heatmap.ColorBar(title=colorbar_label) heatmap = go.Heatmap(z=counts, colorscale=colormap, zmin=vmin, zmax=vmax, x0=extent[0], dx=np.abs((extent[1]-extent[0])/shape), y0=extent[2], dy=
🌐
Plotly
plotly.com › python › annotated-heatmap
Annotated heatmaps in Python
import plotly.express as px import numpy as np np.random.seed(1) z = np.random.randn(20, 20) fig = px.imshow(z, text_auto=".2f", color_continuous_scale='Greys', aspect="auto") fig.show() px.imshow() can produce more elaborate annotated heatmaps. The example below renders a periodic table: the cell labels come from a custom text array, while customdata combined with a hovertemplate displays the element name and atomic mass on hover.
🌐
Plotly
community.plotly.com › 📊 plotly python
Custom tick labels in between ticks on heatmap - 📊 Plotly Python - Plotly Community Forum
November 4, 2022 - I have a heatmap with custom ticks (custom location and custom label). I would like the label to appear in between ticks. So far I managed to get this: import numpy as np import plotly.graph_objects as go np.random.seed(13) N = 100 M = 30 ticks = ['alpha', 'beta', 'gamma', 'zeta', 'theta', 'lambda'] ticks_locations = [0] + np.sort(np.random.randint(0, N, size=len(ticks)-1)).tolist() image = np.random.randn(M, N) fig = go.Figure(data= go.Heatmap( x=np.arange(N) + .5, z=imag...
🌐
Plotly
plotly.com › python › colorscales
Continuous color scales and color bars in Python
Using labelalias, instead of displaying all labels as the numbers in tickvals, we swap out three of the labels for text. ... import plotly.graph_objects as go import urllib.request as request import json # Load heatmap data response = ...
🌐
GitHub
github.com › plotly › plotly.py › blob › main › doc › python › heatmaps.md
plotly.py/doc/python/heatmaps.md at main · plotly/plotly.py
import plotly.graph_objects as go import numpy as np # Build the rectangles as a heatmap # specify the edges of the heatmap squares phi = (1 + np.sqrt(5) )/2.
Author: plotly
Find elsewhere
🌐
Educative
educative.io › answers › how-to-create-a-heatmap-plot-with-plotly-graph-objects-in-python
How to create a heatmap plot with Plotly Graph Objects in Python
It should be a list of lists (or a 2D numpy array) where each element represents a cell's value. x (optional): This is an array or list specifying the labels for the columns of the heatmap.
🌐
GitHub
github.com › plotly › plotly.py › issues › 3651
Heatmap (both go and px) not showing text annotations on Hugo site · Issue #3651 · plotly/plotly.py
March 31, 2022 - Test case: (from https://plotly.com/python/heatmaps/) import plotly.graph_objects as go fig = 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}))
Author: plotly
🌐
Plotly
plotly.com › python-api-reference › generated › plotly.graph_objects.heatmap.html
plotly.graph_objects.heatmap package — 6.6.0 documentation
Sets the spacing between tick labels as compared to the spacing between ticks. A value of 1 (default) means each tick gets a label. A value of 2 means shows every 2nd label. A larger value n means only every nth tick is labeled. tick0 determines which labels are shown.
🌐
Plotly
plotly.com › python › reference › heatmap
Python Figure Reference: heatmap Traces
That means you need to use −1 instead of -1. labelalias can be used with any axis type, and both keys (if needed) and values (if desired) can include html-like tags or MathJax. len Code: fig.update_traces(colorbar_len=<VALUE>, selector=dict(type='heatmap')) Type: number greater than or equal to 0 Default: 1
🌐
GitHub
github.com › plotly › plotly.js › issues › 6226
[BUG] go.Heatmap y axis labels misaligned when using mathjax · Issue #6226 · plotly/plotly.js
June 12, 2022 - When I use strings for y in go.Heatmap with leading and trailing Dollar-signs, the y axis labels lose the alignment (neither left, nor center, nor right. Somehow random).
Author: plotly
🌐
GitHub
github.com › plotly › plotly.py › issues › 1736
Square Heatmap ticks are off · Issue #1736 · plotly/plotly.py
August 23, 2019 - import numpy as np import plotly.offline as py import plotly.graph_objs as go matrix = np.random.randn(10, 10) ticks = ["tick %i" % i for i in range(10)] data = [go.Heatmap(z=matrix, x=ticks, y=ticks, colorscale='Viridis')] layout = go.Layout( hovermode='closest', autosize=True, xaxis=dict(zeroline=False), yaxis=dict(zeroline=False, autorange='reversed', scaleanchor="x", scaleratio=1) ) fig = go.Figure(data=data, layout=layout) py.iplot(fig) Produces this plot: I think there really shouldn't be this space between the y ticks and colorbar and the heatmap. Without the yaxis scaleanchor="x" it looks fine, but I really want a square heatmap... Is there any setting I'm missing or is this a bug? Thanks! No one assigned · No labels ·
Author: plotly
🌐
GeeksforGeeks
geeksforgeeks.org › python › annotated-heatmaps-using-plotly-in-python
Annotated Heatmaps using Plotly in Python - GeeksforGeeks
September 5, 2020 - import plotly.figure_factory as ff import numpy as np feature_x = np.arange(0, 10, 2) feature_y = np.arange(0, 10, 3) # Creating 2-D grid of features [X, Y] = np.meshgrid(feature_x, feature_y) Z = np.cos(X / 2) + np.sin(Y / 4) fig = ff.create_annotated_heatmap(Z, colorscale='rainbow') fig.show()
🌐
Delft Stack
delftstack.com › home › howto › plotly › plotly heatmap
How to Plot Heatmap in Plotly | Delft Stack
February 2, 2024 - Let’s use a random matrix to create a heatmap. See the code below. import plotly.graph_objects as go z = [[1, 10, 20], [30, 1, 10], [20, 30, 1]] data = go.Heatmap(z=z) fig = go.Figure(data) fig.show()
🌐
Plotly
community.plotly.com › dash python
Error Showing Text Labels in Heatmap - Dash Python - Plotly Community Forum
December 28, 2021 - I am trying to render text labels on a Heatmap. I have verified that I am running the latest version of Plotly (5.5.0), and am using the example code in the “Text on Heatmap Points” section on the Heatmaps webpage (Heatmaps). My code looks like the following: from dash import Dash, dcc, html import plotly.graph_objects as go figHeatmap = go.Figure( data=go.Heatmap( z=[[1,20,30], [20,1,60], [30,60,1]], ...
🌐
GeeksforGeeks
geeksforgeeks.org › python › create-heatmaps-using-graph_objects-class-in-plotly
Create Heatmaps using graph_objects class in Plotly - GeeksforGeeks
September 5, 2020 - import plotly.graph_objects as go feature_x = np.arange(0, 50, 2) feature_y = np.arange(0, 50, 3) # Creating 2-D grid of features [X, Y] = np.meshgrid(feature_x, feature_y) Z = np.cos(X / 2) + np.sin(Y / 4) fig = go.Figure(data=go.Heatmap( x=feature_x, y=feature_y, z=Z,)) fig.update_layout( margin=dict(t=200, r=200, b=200, l=200), showlegend=False, width=700, height=700, autosize=False) fig.show()
🌐
Plotly
community.plotly.com › 📊 plotly python
Shorten axis text in heatmap - 📊 Plotly Python - Plotly Community Forum
December 7, 2023 - Hi all, I’m trying to shorten long text labels on the y-axis of a heatmap, where the y-axis has a nested-type structure. Example: import numpy as np import plotly.graph_objects as go x = ['1','2'] y = np.array( [ ['Veryveryveryveryveryverylong1', 'Veryveryveryveryveryverylong1','short', 'short'], ['A', 'B', 'A', 'B'] ] ) z = np.random.rand(4,2) fig = go.Figure() fig.add_trace(go.Heatmap(x=x, y=y, z=z)) What I’d like, is the Veryveryveryveryveryverylong1 label to be...