Python Plotly子图指定位置添加十字标记的实现问题
在Plotly子图指定位置添加十字标记
要在两个热力图子图的指定位置添加十字标记,可以通过Plotly的**形状(shape)**功能实现,核心是为每个子图的坐标轴设置对应的参考标识(x1/y1对应第一个子图,x2/y2对应第二个子图),然后绘制十字的水平和垂直线段。
修改后的完整代码
import numpy as np import plotly.graph_objs as go import plotly.figure_factory as ff from plotly.subplots import make_subplots import string # 定义热力图数据 N=5 x = np.array([10*k for k in range(N)]) y = np.linspace(0, 2, N) z1 = np.random.randint(5,15, (N,N)) z2 = np.random.randint(10,27, (N,N)) mytext = np.array(list(string.ascii_uppercase))[:25].reshape(N,N) fig1 = ff.create_annotated_heatmap(z1, x.tolist(), y.tolist(), colorscale='matter') fig2 = ff.create_annotated_heatmap(z2, x.tolist(), y.tolist(), annotation_text=mytext, colorscale='Viridis') fig = make_subplots( rows=1, cols=2, horizontal_spacing=0.05, ) fig.add_trace(fig1.data[0], 1, 1) fig.add_trace(fig2.data[0], 1, 2) # 转移原热力图的注释 annot1 = list(fig1.layout.annotations) annot2 = list(fig2.layout.annotations) for k in range(len(annot2)): annot2[k]['xref'] = 'x2' annot2[k]['yref'] = 'y2' fig.update_layout(annotations=annot1+annot2) # ---------------------- 添加十字标记的核心代码 ---------------------- # 定义两个子图中要标记的位置(可根据需求修改坐标) mark_positions = [ {'subplot': '1', 'x': 20, 'y': 1}, # 第一个子图的标记点 {'subplot': '2', 'x': 30, 'y': 0.8} # 第二个子图的标记点 ] # 为每个标记点绘制十字 for pos in mark_positions: x_ref = f'x{pos["subplot"]}' y_ref = f'y{pos["subplot"]}' mark_x = pos['x'] mark_y = pos['y'] # 添加垂直线段(十字竖线) fig.add_shape( type='line', x0=mark_x, y0=y.min(), x1=mark_x, y1=y.max(), xref=x_ref, yref=y_ref, line=dict(color='red', width=2, dash='dash') ) # 添加水平线段(十字横线) fig.add_shape( type='line', x0=x.min(), y0=mark_y, x1=x.max(), y1=mark_y, xref=x_ref, yref=y_ref, line=dict(color='red', width=2, dash='dash') ) fig.show()
关键说明
- 十字标记由水平线段和垂直线段组合而成,分别覆盖子图的整个y轴范围和x轴范围
- 通过
xref和yref指定线段所属的子图:第一个子图用x1/y1,第二个子图用x2/y2 - 可自行修改
mark_positions中的坐标值调整标记位置,也可修改line参数调整线条的颜色、粗细和样式
内容的提问来源于stack exchange,提问作者bluered_earth
相关产品推荐
相关产品推荐

