Overlay values as text in a PlotlyJS heatmap annotations

Hi,
My code is rather simple:

using PlotlyJS
plot(heatmap(x=["a","b"],y=["c","d"],z=rand(2,2),colorscale="Reds",showscale=false))

I’m trying to have the values as an overlay (say black text) on each of the 4 squares. In Python I’d be using plotly’s annotations, but couldn’t really find how to do that with the Julia version. Any hint appreciated.

Could you post a link or short example of the Python version with an image of what you’re aiming for?

A sample output I’m getting in Python is as follows:

I will try to come up with a minimum working example in python, but the steps are a manual creation of a plotly.graph_objects.Figure() figure with rectangular shapes and annotations manually crafted.

Edit: not my code, but some sample python plotly code achieving a similar result at stack overflow

I would first define the plot trace (data) separate to the layout options; annotations are added in layouts, not traces. So a simple example:

trace = heatmap(x=["a","b"],y=["c","d"],z=rand(2,2),
              colorscale="Reds",
              showscale=false)

layout = Layout(
       annotations=[
           attr(x=0.25, y=0.25, text=1),
           attr(x=0.25, y=0.75, text=2), 
           attr(x=0.75, y=0.25, text=3),
           attr(x=0.85, y=0.95, text=4, showarrow=false)
           ],
           font=attr(size=20))

plot(trace, layout)

If you want to get more involved, consider this example: Annotated Heatmap

Unfortunately, there is currently no equivalent in the Julia Plotly examples, but you can adapt most JavaScript examples by remembering to use the notation font=attr(family="Arial", size=12) in place of the JavaScript equivalent

font: {
        family: 'Arial',
        size: 12,
}

Full options for annotations are described here: annotations

Thank you, this is pretty similar to what I use in Python but was getting the annotations construction wrong.
Note that x="a", y="c" entries are accepted and take care of the centering/alignment for you.
Much appreciated JD.

1 Like

If @sglyon were to update PlotlyJS.jl to be compatible with the latest version of plotly.js, then an annotated heatmap could be simply defined as follows:

using PlotlyJS
pl= Plot(heatmap(z=rand(2:15, (3,3)),
                    text=[["A", "Ab", "C"],
                          ["Cd", "E", "Ef"],
                          ["G", "Gh", "Kl"]],
                    texttemplate="%{text}",
                    colorscale=colors.matter))
relayout!(pl, width=500, height=500, font_size=10)
display(pl)
1 Like