gpt4 book ai didi

python - plotly :从hoverlabels隐藏 `null`

转载 作者:行者123 更新时间:2023-12-04 11:29:43 27 4
gpt4 key购买 nike

我有一个名为 my_customdata 的列表其中有一些 nan值。当我绘制森伯斯特图表并将我的列表传递给 customdata 时,它会根据需要显示值。但是对于nan值,而是显示 0 (如果我将 si 前缀设置与 customdata 一起传递)或 null如果我没有传递自定义 si 前缀格式。仅当存在 nan 时,我才想隐藏悬停标签中的数据在列表中。有可能这样做吗?
enter image description here

import pandas as pd
import plotly.express as px
import numpy as np


data = {
'ids':['SA', 'NA', 'Brazil', 'Uruguay', 'USA', 'Canada', 'PFV Brazil', 'PV Brazil', 'PFV Uruguay', 'PV Uruguay', 'PFV USA', 'PV USA', 'PFV Canada', 'PV Canada'],
'labels': ['SA', 'NA', 'Brazil', 'Uruguay', 'USA', 'Canada', 'PFV', 'PV', 'PFV', 'PV', 'PFV', 'PV', 'PFV', 'PV'],
'parent': ['', '', 'SA', 'SA', 'NA', 'NA', 'Brazil', 'Brazil', 'Uruguay', 'Uruguay', 'USA', 'USA', 'Canada', 'Canada'],
'value': [0, 0, 100, 100, 400, 200, 8, 40, 4, 20, 11, 80, 11, 80]
}
my_customdata = [x/780*100 if x>80 else np.nan for x in data['value']]
my_customdata[0] = 200/780*100
my_customdata[1] = 600/780*100

fig =px.sunburst(data, names='labels', parents='parent', values='value', ids='ids', color='value',
color_continuous_scale='Blues')

fig.update_traces(customdata=my_customdata, hovertemplate='%{label}<br>%{customdata:,.5s}')
fig.show()

最佳答案

基于 here 的答案,同样可以应用于这个问题以获得有效的解决方案。 (事实上​​,它是解决所有 plotly 悬停标签问题的一站式解决方案!)

import pandas as pd
import plotly.express as px
import numpy as np


data = {
'ids':['SA', 'NA', 'Brazil', 'Uruguay', 'USA', 'Canada', 'PFV Brazil', 'PV Brazil', 'PFV Uruguay', 'PV Uruguay', 'PFV USA', 'PV USA', 'PFV Canada', 'PV Canada'],
'labels': ['SA', 'NA', 'Brazil', 'Uruguay', 'USA', 'Canada', 'PFV', 'PV', 'PFV', 'PV', 'PFV', 'PV', 'PFV', 'PV'],
'parent': ['', '', 'SA', 'SA', 'NA', 'NA', 'Brazil', 'Brazil', 'Uruguay', 'Uruguay', 'USA', 'USA', 'Canada', 'Canada'],
'value': [0, 0, 100, 100, 400, 200, 8, 40, 4, 20, 11, 80, 11, 80]
}
my_customdata = [x/780*100 if x>80 else np.nan for x in data['value']]
my_customdata[0] = 200/780*100
my_customdata[1] = 600/780*100

fig =px.sunburst(data, names='labels', parents='parent', values='value', ids='ids', color='value',
color_continuous_scale='Blues')

df = pd.DataFrame(my_customdata)

def human_format(num):
num = float('{:.3g}'.format(num))
magnitude = 0
while abs(num) >= 1000:
magnitude += 1
num /= 1000.0
return '{}{}'.format('{:f}'.format(num).rstrip('0').rstrip('.'),
['', 'K', 'M', 'B', 'T'][magnitude])

df["hover_data"] = df.apply(lambda r:f"{human_format(r[0])}",axis=1)
df = df.replace('nan','')

fig.update_traces(customdata=df['hover_data'], hovertemplate='%{label}<br>%{customdata}')
fig.show()
enter image description here

关于python - plotly :从hoverlabels隐藏 `null`,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68004684/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com