Plotly实现单页面展示多个独立非子图图表
实现方法
目标单图表效果如下:
你代码里两个核心错误导致效果不符合预期:
- 行计数器
count放在了大区遍历循环内部,每次处理新大区都会重置为1,所有大区的曲线会被错叠到前几行子图里 - Plotly subplots默认使用全局共用图例,你直接设置
showlegend=False关了全局图例,自然没法给每个子图配独立图例
按下面的逻辑改就能实现单页展示所有独立图表:
- 把行计数器移到大区循环外初始化,每处理完一个大区再自增,保证每个大区的所有曲线落在对应行的子图中
- 创建subplots时传入
subplot_titles参数,直接给每个子图生成对应大区的独立标题 - 给每一行子图单独创建图例实例,把当前大区的所有曲线绑定到对应图例,再把每个图例定位到对应子图的右上角,实现每个子图自带独立图例的效果
- 逐行给子图配置坐标轴属性,不用全局统一设置坐标轴
修正后的可运行代码:
import pandas as pd import plotly.graph_objects as go from plotly.subplots import make_subplots def camasRegion(): df = pd.read_csv('https://raw.githubusercontent.com/MinCiencia/Datos-COVID19/master/output/producto52/Camas_UCI.csv') Regiones = df['Region'].drop_duplicates().tolist() total_regions = len(Regiones) fig = make_subplots( rows=total_regions, cols=1, subplot_titles=Regiones, vertical_spacing=0.08 ) row_idx = 1 for region in Regiones: target_data = df.query('Region == @region').drop('Region', axis=1).set_index('Serie').T for col in target_data.columns: if col == 'Camas base (2019)': continue fig.add_trace( go.Scatter( x=target_data.index, y=target_data[col], name=col, mode='lines', legend=f"legend{row_idx}", legendgroup=col ), row=row_idx, col=1 ) fig.update_xaxes(title_text="Días", row=row_idx, col=1) fig.update_yaxes(title_text="Cantidad de camas", row=row_idx, col=1) fig.update_layout(**{ f"legend{row_idx}": { "xanchor": "right", "yanchor": "top", "x": 0.98, "y": 1 - (row_idx-1)/total_regions - 0.02, "font": {"size": 9} } }) row_idx += 1 fig.update_layout( template='plotly_white', hovermode='x', height=total_regions * 400, margin=dict(l=50, r=150, t=50, b=80) ) fig.add_annotation( x = 1, y = 0, text = 'Fuente: Datos obtenidos desde el Ministerio de Ciencia:', showarrow = False, xref='paper', yref='paper', xanchor='right', yanchor='auto', yshift=-30 ) fig.show() camasRegion()
运行后会在单个页面垂直排列17个大区的完整图表,每个图表都带独立标题、坐标轴、图例,不会弹出多个窗口。如果要调整子图间距、图例大小、页面总高度,直接修改对应布局参数即可。
内容的提问来源于stack exchange,提问作者MrPie
相关产品推荐
相关产品推荐

