Shorten axis text in heatmap

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))

image

What I’d like, is the Veryveryveryveryveryverylong1 label to be shortened to Veryveryve... or something (but still displaying the full label via the tooltip).

I tried altering the ticktext, like

import pandas as pd

y_ser = pd.Series(y[0])
y_0 = np.where(y_ser.str.len() > 10, y_ser.str[:10] + "...", y_ser)
new_y = np.array([y_0, y[1]])

fig.update_layout(
    yaxis = {
        'tickmode': 'array',
        'tickvals': y,
        'ticktext': new_y
    }
)

(and several options around this) but this just removes the y-axis labels completely.

Very grateful for any suggestions!

Hi @Al_V ,

Because I have tried you code and it does make y axis disappeared.
So I came up with solution but maybe this is mix with my creativity :grin:

The idea is using text and hovertemplate keywords.

the y axis data will filled with your new_y (from your code) which is the short version of y axis.

the text keyword will be filled with a list of the hover text for y axis with long text.

text=[ [str(y_val0)+"-"+str(y_val1),str(y_val0)+"-"+str(y_val1)] for y_val0,y_val1 in zip(y[0],y[1])]

the hovertemplate keyword will put all x,y,z hovered text, and for y hover value will be replace value from text.

the implementation of this scenario is like code below.

import numpy as np
import pandas as pd
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)


y_ser = pd.Series(y[0])
y_0 = np.where(y_ser.str.len() > 10, y_ser.str[:10] + "...", y_ser)
new_y = np.array([y_0, y[1]])
print(new_y)


fig = go.Figure()
fig.add_trace(go.Heatmap(
	x=x,
	y=new_y,
	z=z,
	text=[ [str(y_val0)+"-"+str(y_val1),str(y_val0)+"-"+str(y_val1)] for y_val0,y_val1 in zip(y[0],y[1])],
	hovertemplate =
	'x : %{x}<br>'+
	'y : %{text}<br>'+
	'z : %{z}',
	name="",
	))

fig.show()	

Hope this help.

2 Likes

@farispriadi many thanks - it looks like there isn’t a built-in for this, so your solution is a great alternative!

For others who come here - @farispriadi’s solution works well for my original example, with two columns. To extend to any number of columns, try something like text = [[y0 + " - " + y1 for _ in x] for y0, y1 in zip(y[0], y[1])]

1 Like