我有以下代码可以在 Google colab 中使用plotly 生成旭日图。
import plotly.express as px
import matplotlib.pyplot as plt
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))
# Set everything to grey initially
sample_df['color'] = 'grey'
if person != 'all_greyscale':
# Get the B values associated with the current person
Bs = sample_df[sample_df[person].str.strip() == '1']['B'].tolist()
# Color those specific B values
sample_df.loc[sample_df['B'].isin(Bs), 'color'] = color_hex
# Identify the unique A values for those specific B values
As = sample_df[sample_df['B'].isin(Bs)]['A'].unique()
# Color only those specific A entries
for A in As:
sample_df.loc[(sample_df['A'] == A) & (sample_df['B'] == ''), 'color'] = color_hex
# Create the sunburst diagram with a fixed color mapping
fig = px.sunburst(sample_df,
path=['A', 'B'],
color='color',
color_discrete_map={'grey': 'grey', color_hex: color_hex},
title=f'Sunburst highlighting {person}')
# Remove the temporary 'color' column
sample_df.drop('color', axis=1, inplace=True)
return fig
def get_color_for_person(person_name):
# Map each unique name to a unique number between 0 and 1
unique_names = sample_df.columns[2:].tolist() # Assuming the person columns start at index 2
num_people = len(unique_names)
name_mapping = {name: idx/num_people for idx, name in enumerate(unique_names)}
# Get the color for the person using the viridis colormap
colormap = plt.cm.viridis
return colormap(name_mapping[person_name])
import pandas as pd
# Creating a new sample dataset
data = {
'A': ['Dolor', 'Dolor', 'Sit', 'Sit', 'Amet', 'Amet'],
'B': ['', 'Consectetur', 'Adipiscing', '', 'Elit', 'Sed'],
'Jessica Smith': ['', '1', '', '1', '1', ''],
'Thomas Brown': ['1', '', '1', '', '', '1'],
}
sample_df = pd.DataFrame(data)
# Generate a sunburst for 'Jessica Smith' for debugging
fig = generate_single_color_sunburst('Jessica Smith', get_color_for_person('Jessica Smith'))
fig.show()
这产生了这个情节:
问题是我也希望“Amet”和“Sit”是紫色的。换句话说,当任何 B 被着色时,我希望相应的 A 也被着色。感谢您的建议。
“当任何 B 被着色时,我希望相应的 A 也被着色”:所以当所有 B 都被着色时,这非常有效。
但是在“Amet”或“Sit”的情况下(在您的示例中),当只有一个 B 被着色时,则分层树结构/旭日图中的父级(示例中的“A”)将具有该颜色颜色栏为
'?'
(见下图)。
我认为发生这种情况是因为它无法聚合两种不同的颜色值。
一种解决方法是在 color_discrete_map 中显式添加该情况的键,如下所示:
color_discrete_map={'grey': 'grey', color_hex: color_hex,'(?)': color_hex}
fig = px.sunburst(sample_df,
path=['A', 'B'],
color='color',
color_discrete_map=color_discrete_map,
title=f'Sunburst highlighting {person}')
希望这有帮助。
输出: