Irregular gaps in plotly heatmaps

241 Views Asked by At

I have a question about paddings in plotly heatmaps. Indeed if i want to make a regular space between all cells of my heatmap I juste need to do this :

data = np.random.uniform(size= (5,5))
fig = go.Figure(data=go.Heatmap(z = data,
                                xgap= 5,
                                ygap= 5,
                                colorscale="RdBu_r"))

But, the thing I want is, for example, to left a space each 2 cells in order to make squares of 4, or more. This will give something like this : enter image description here

Is there a way to do this in plotly ?

Thank you in advance

1

There are 1 best solutions below

4
Achraf Ben Salah On

You can achieve this by customizing the x and y axes tick labels and then adjusting the xgap and ygap parameters accordingly.

Like this :

import numpy as np
import plotly.graph_objs as go

# Random data array 
data = np.random.uniform(size=(5, 5))
data_with_gaps = np.zeros((9, 9))
data_with_gaps[::2, ::2] = data

# Define values for x and y axes
x_ticks = ['A', '', 'B', '', 'C', '', 'D', '', 'E']
y_ticks = ['1', '', '2', '', '3', '', '4', '', '5']

fig = go.Figure(data=go.Heatmap(
    z=data_with_gaps,
    x=x_ticks,
    y=y_ticks,
    colorscale="RdBu_r"
))

fig.show()

Output :

[1]: https://i.stack.imgur.com/tX9Sz.png

[EDIT] :

Finally, plotly does not have a built-in feature to directly reduce the size of a specific row or column. you may need to consider alternative approaches, such as creating custom grid-like visualizations using scatter plots, annotations, or custom shapes in Plotly. Here's an example

import plotly.graph_objects as go
import numpy as np

data = np.random.uniform(size=(5, 5))

# Create a custom grid with reduced size for row 2 and column 4
fig = go.Figure()

for i in range(5):
    for j in range(5):
        cell_size = 0.9  # Adjust the size as needed
        x0 = j - cell_size / 2
        y0 = 4 - i - cell_size / 2
        x1 = j + cell_size / 2
        y1 = 4 - i + cell_size / 2

        # Reduce the size for row 2 and column 4
        if i == 2:
            y0 += 0.1
        if j == 4:
            x1 -= 0.1

        fig.add_shape(
            type="rect",
            x0=x0,
            y0=y0,
            x1=x1,
            y1=y1,
            fillcolor="black",  # Adjust the color as needed
            opacity=0.7,  # Adjust the opacity as needed
            line=dict(width=0),
        )

# Set the axis properties
fig.update_xaxes(range=[-0.5, 4.5])
fig.update_yaxes(range=[-0.5, 4.5], scaleanchor="x")

fig.show()