如何在Plotly Express的px.line_polar雷达图中添加多条线?
实现方法建议
方法1:合并数据框,利用Plotly Express的分组功能(推荐)
Plotly Express的line_polar更适配结构化分组数据,先给两个DataFrame新增分组标识列,合并后直接通过color参数区分组别,自动生成图例:
import plotly.express as px import pandas as pd df1 = pd.DataFrame(dict( r=[1, 5, 2, 2, 3], theta=['processing cost', 'mechanical properties', 'chemical stability', 'thermal stability', 'device integration'])) df1['group'] = 'Group 1' # 给df1添加分组标识 df2 = pd.DataFrame(dict( r=[.1, .5, .2, .2, .3], theta=['processing cost', 'mechanical properties', 'chemical stability', 'thermal stability', 'device integration'])) df2['group'] = 'Group 2' # 给df2添加分组标识 # 合并两个数据框 combined_df = pd.concat([df1, df2]) # 绘制雷达图,color参数控制分组,自动生成图例 fig = px.line_polar(combined_df, r='r', theta='theta', color='group', line_close=True) fig.show()
方法2:通过add_trace手动添加第二条线
如果不想合并数据框,可先基于df1生成雷达图,再用add_trace添加df2对应的Scatterpolar对象,通过name参数指定图例名称:
import plotly.express as px import plotly.graph_objects as go import pandas as pd df1 = pd.DataFrame(dict( r=[1, 5, 2, 2, 3], theta=['processing cost', 'mechanical properties', 'chemical stability', 'thermal stability', 'device integration'])) df2 = pd.DataFrame(dict( r=[.1, .5, .2, .2, .3], theta=['processing cost', 'mechanical properties', 'chemical stability', 'thermal stability', 'device integration'])) # 先绘制df1的雷达图,指定name显示图例 fig = px.line_polar(df1, r='r', theta='theta', line_close=True, name='Group 1') # 添加df2的雷达线 fig.add_trace(go.Scatterpolar( r=df2['r'], theta=df2['theta'], line_close=True, name='Group 2' )) fig.show()
两种方法都能实现需求:方法1更贴合Plotly Express的设计逻辑,代码简洁易维护;方法2适合需要单独控制单条线样式的场景。
内容的提问来源于stack exchange,提问作者Natasha
相关产品推荐
相关产品推荐

