Plotly旭日图着色需求:子节点变色时同步父节点颜色
解决方案
问题出在你给A父节点着色的逻辑上,当前代码的匹配条件没有覆盖到所有需要着色的父节点。只要某个A节点下有任意子B节点被标记为目标用户,就需要把对应的A父节点(即B == ''的行)设为目标颜色,修改后的代码如下:
def generate_single_color_sunburst(person, color): color_hex = "#{:02x}{:02x}{:02x}".format(int(color[0]*255), int(color[1]*255), int(color[2]*255)) # 初始化所有节点为灰色 sample_df['color'] = 'grey' if person != 'all_greyscale': # 提取当前用户标记为'1'的所有行 target_rows = sample_df[sample_df[person].str.strip() == '1'] # 获取关联的B节点值和对应的父A节点值 target_Bs = target_rows['B'].tolist() target_As = target_rows['A'].unique() # 为匹配的B节点着色 sample_df.loc[sample_df['B'].isin(target_Bs), 'color'] = color_hex # 为所有包含目标B节点的A父节点(B为空的行)着色 sample_df.loc[(sample_df['A'].isin(target_As)) & (sample_df['B'] == ''), 'color'] = color_hex # 生成旭日图 fig = px.sunburst(sample_df, path=['A', 'B'], color='color', color_discrete_map={'grey': 'grey', color_hex: color_hex}, title=f'Sunburst highlighting {person}') # 删除临时color列 sample_df.drop('color', axis=1, inplace=True) return fig
关键改动说明:
- 直接从标记了目标用户的行中提取父A节点集合,确保不会遗漏任何包含子B节点的A节点
- 简化A父节点的着色条件:只要A属于目标集合且B为空,就设置为目标颜色,不再依赖该行的用户标记值
修改后,生成Jessica Smith的旭日图时,Sit和Amet这两个A父节点会和对应的子B节点同步变为紫色,满足需求。
内容的提问来源于stack exchange,提问作者Ken Reid
相关产品推荐
相关产品推荐

