本文共 1570 字,大约阅读时间需要 5 分钟。
在Plotly中,实现多个子图共享图例并构造填充面的过程可以通过plotly.subplots模块来完成。以下是实现步骤和代码示例:
import plotly.graph_objs as gofrom plotly.subplots import make_subplotsimport numpy as np
2. **准备数据** 假设我们生成三个不同形状的3D图形的数据,并分别对应不同的子图和图例项。 ```python # 创建数据 x1, y1, z1 = np.random.rand(3, 50) x2, y2, z2 = np.random.rand(3, 50) + 1 x3, y3, z3 = np.random.rand(3, 50) + 2 # 数据准备 data1 = go.Scatter3d(x=x1, y=y1, z=z1, mode='markers', name='Group A') data2 = go.Scatter3d(x=x2, y=y2, z=z2, mode='lines', name='Group B') data3 = go.Scatter3d(x=x3, y=y3, z=z3, mode='markers+text', text=[f'Point {i}' for i in range(50)], textposition="top right", name='Group C') fig = make_subplots(rows=2, cols=2, shared_xaxes=True, shared_yaxes=True, vertical_spacing=0.1, horizontal_spacing=0.1)
4. **在各子图中添加3D图形,并隐藏图例** ```python fig.add_trace(data1, row=1, col=1, showlegend=False) fig.add_trace(data2, row=1, col=2, showlegend=False) fig.add_trace(data3, row=2, col=1, showlegend=False)
legend_items = [ go.Scatter3d(x=[], y=[], z=[], mode='markers', name='Group A'), go.Scatter3d(x=[], y=[], z=[], mode='lines', name='Group B'), go.Scatter3d(x=[], y=[], z=[], mode='markers+text', text=[], textposition="top right", name='Group C')]
6. **添加合并后的图例到主图** ```python fig.update_layout(showlegend=True, legend=dict(items=legend_items))
fig.show()
这个例子中,我们创建了三个子图:一个包含点标记的Group A,一个包含线段的Group B,以及一个包含点标记和文本标签的Group C。由于每个子图的图例项都相同(即名字相同),所以合并后的主图图例将只显示一个图例项。在数据可视化中,共享图例可以帮助用户更清晰地理解不同数据集之间的关系。例如,在一个多变量分析中,你可以创建多个子图来展示不同特征之间的关系,然后通过共享图例来标注不同的变量或类别。
转载地址:http://cgtfk.baihongyu.com/