绘图热图中的不规则间隙

问题描述 投票:0回答:1

我有一个关于绘图热图中填充的问题。事实上,如果我想在热图的所有单元格之间形成规则的空间,我只需要这样做:

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

但是,我想要的是,例如,每 2 个单元格留一个空间,以便形成 4 个或更多的正方形。这将给出类似这样的内容:

有没有办法在情节中做到这一点?

提前谢谢您

python plotly heatmap plotly.graph-objects
1个回答
1
投票

您可以通过自定义 xy 轴刻度标签,然后相应调整 xgap 和 ygap 参数来实现此目的。

像这样:

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

输出:

[编辑]:

最后,plotly 没有内置功能来直接减小特定行或列的大小。您可能需要考虑替代方法,例如使用散点图、注释或 Plotly 中的自定义形状创建自定义的类似网格的可视化效果。这是一个例子

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()
© www.soinside.com 2019 - 2024. All rights reserved.