如何在 plotly express treemap 中添加计数器和求和
How to add counter and sum in plotly express treemap
如何在plotly treemap中为扇区添加计数器和总和?
当前结果(无计数器,无总和):
“亚洲”、“非洲”
理想结果(名称后有 COUNT 和 SUM):
“亚洲 2 个国家,41MM”,“非洲 2 个国家,37MM”
尚未在文档和 Stack Overflow 中找到任何内容。
代码
import pandas as pd
import plotly.express as px
data = {'Category':['Asia', 'Asia', 'Africa', 'Africa'],
'Name':['Country 1', 'Country 2', 'Country 3', 'Country 4'],
'Amount':[20, 21, 19, 18]}
df = pd.DataFrame(data)
fig = px.treemap(df,
path=['Category','Name'],
values='Amount')
fig.update_traces(textinfo='value')
fig.show()
最好我想知道如何在 plotly lib 中本地执行此操作。不过,解决方法也很有用。
您可以使用此代码:
parent = fig.data[0]['parents']
child = fig.data[0]['labels']
for i,j in zip(*np.unique(parent, return_counts=True)):
if i != '':
#parent[parent == i] = i+' '+str(j) # if you have only a root, uncomment this line
child[child == i] = i+' '+str(j)
如何在plotly treemap中为扇区添加计数器和总和?
当前结果(无计数器,无总和):
“亚洲”、“非洲”
理想结果(名称后有 COUNT 和 SUM):
“亚洲 2 个国家,41MM”,“非洲 2 个国家,37MM”
尚未在文档和 Stack Overflow 中找到任何内容。
代码
import pandas as pd
import plotly.express as px
data = {'Category':['Asia', 'Asia', 'Africa', 'Africa'],
'Name':['Country 1', 'Country 2', 'Country 3', 'Country 4'],
'Amount':[20, 21, 19, 18]}
df = pd.DataFrame(data)
fig = px.treemap(df,
path=['Category','Name'],
values='Amount')
fig.update_traces(textinfo='value')
fig.show()
最好我想知道如何在 plotly lib 中本地执行此操作。不过,解决方法也很有用。
您可以使用此代码:
parent = fig.data[0]['parents']
child = fig.data[0]['labels']
for i,j in zip(*np.unique(parent, return_counts=True)):
if i != '':
#parent[parent == i] = i+' '+str(j) # if you have only a root, uncomment this line
child[child == i] = i+' '+str(j)