Assigning colours to groups of rows/columns in Python Plotly heatmaps

Viewed 437

Is there a way to use plotly in Python to generate a heatmap (e.g., through imshow) and assign different colours to different groups of rows/columns? The goal is to generate a plot similar to the clustermap that can be generated with seaborn without dendrograms but with external colours of the rows/columns to indicate distinct groups, as shown in the example attached here below and obtained from seaborn's documentation where rows are assigned with different colours for indicating species:

lut = dict(zip(species.unique(), "rbg"))
row_colors = species.map(lut)
g = sns.clustermap(iris, row_colors=row_colors)

In particular, is there a solution to this using plotly.express and starting from (or using directly) data within a pandas's DataFrame?

final goal obtained with seaborn

1 Answers

Adding colours to distinguish groups of rows/columns on a Heatmap can be achieved using subplots, where one row/column hetamaps are used to distinguish groups. An example is shown here below:

fig = make_subplots(rows=2, cols=2, column_widths=[0.9, 0.1], row_heights=[0.9, 0.1], vertical_spacing=0.02)
table = pd.pivot_table(df, index='A', columns='B', values='C', aggfunc='first')
fig.append_trace(go.Heatmap(z=table, colorscale = 'bugn', colorbar={'x' : 1.1, 'y' : 0.5}), row=1, col=1)
fig.append_trace(go.Heatmap(z=df1, colorscale='spectral', showscale=False), row=1, col=2)
fig.append_trace(go.Heatmap(z=df2, colorscale='plasma', showscale=False), row=2, col=1)
fig.update_layout(xaxis2_showticklabels=False, yaxis2_showticklabels=False,
                  xaxis3_showticklabels=False, yaxis3_showticklabels=False,
                  xaxis_side='top')
fig.show()

enter image description here

Related