A heatmap encodes a matrix as colour, and the whole picture depends on one decision: how numbers map to colours. Plotly stretches the colour scale over the data's own minimum and maximum unless told otherwise, so two heatmaps of two different matrices can use "red" to mean different numbers, and a correlation matrix whose largest off-diagonal entry is 0.3 can be painted as vividly as one that reaches 0.95. Pinning the range (zmin, zmax), centring a diverging scale on zero (zmid) and labelling the colourbar make the colours comparable and readable.
Colours alone are imprecise, so the cells that matter get their value written on them. This question builds a general heatmap with an explicit scale, the correlation-matrix heatmap that applies it, and a function that annotates only the cells above a threshold, which is how a reader's eye is guided to the strong relationships.
Implement heatmap_figure(z, x_labels, y_labels, title, zmin, zmax, colorscale), correlation_heatmap(df) and annotate_strong_cells(fig, z, x_labels, y_labels, threshold). The signatures and docstrings are already in the editor.
plotly.graph_objects. Do not call fig.show().heatmap_figure returns a go.Figure with one Heatmap trace: z is the matrix (a list of rows), x the column labels, y the row labels, the given colorscale, colour range zmin to zmax, a colourbar whose title is "value", and the layout title title.correlation_heatmap(df) returns the heatmap of the Pearson correlation matrix of the numeric columns of df (labels = column names on both axes), colour scale "RdBu", range fixed to -1 to 1 and centred at 0 (zmid=0), with every cell labelled with its value to two decimals (texttemplate="%{z:.2f}").annotate_strong_cells(fig, z, x_labels, y_labels, threshold) adds one annotation for every cell whose absolute value is at least threshold: the text is the value to two decimals (f"{v:.2f}"), positioned at that cell (x = its column label, y = its row label), without an arrow (showarrow=False). It returns the number of annotations added, as an int.go.Heatmap(z=..., x=..., y=..., colorscale=..., zmin=..., zmax=..., colorbar=dict(title=dict(text="value"))).
zmid=0 centres a diverging scale at zero. Set zmin/zmax as well so the range is symmetric.
fig.add_annotation(x=..., y=..., text=..., showarrow=False) places text in data coordinates.
No results yet
Run your code to check it against the examples, or submit to run every test.