pythonplotlyplotly-python

Plotly: How to change the tick text of the colorbar in a Heatmap


I am using Plotly package for my visualizations.
This MWE creates a 10x10 matrix and plots it in a Heatmap.

import numpy as np
import pandas as pd
import plotly.graph_objects as go

vals = np.random.rand(10,10)*5
vals = np.around(vals)

tick_text = ['A','B','C','D','E']

df = pd.DataFrame(vals)

fig = go.Figure(go.Heatmap(
    z=df.values,
    x = df.index,
    y = df.columns
))
fig.update_layout(
    height=500,
    width=500
)
fig.update_layout(
            coloraxis_colorbar=dict(
                tickmode = 'array',
                tickvals = [i for i in range(5)],
                ticktext = tick_text,
            )
            )
fig.show()

This is the output
enter image description here

I am trying to change the text displayed next to the colorbar. In this case I want to see A,B,C,D,E instead of 1,2,3,4,5.
I followed the documentation and as far as i understood i have to change coloraxis_colorbar but this doesn't seem to work.


Solution

  • You also need to specify the coloraxis the trace should refer to when building the heatmap.

    coloraxis - Sets a reference to a shared color axis. References to these shared color axes are "coloraxis", "coloraxis2", "coloraxis3", etc. Settings for these shared color axes are set in the layout, under layout.coloraxis, layout.coloraxis2, etc.

    Just add this line, and your code should work as expected :

    fig = go.Figure(go.Heatmap(
        z=df.values,
        x = df.index,
        y = df.columns,
        coloraxis='coloraxis'  # <- here 
    ))