2 回答
TA贡献1811条经验 获得超6个赞
如果我正确理解您的问题,您希望更改图例中显示的内容,而不更改数据源中的名称。可能有更优雅的方法可以做到这一点,但我已经组合了一个自定义函数newLegend(fig, newNames)
来为您完成此任务。
因此,对于这样的数字:
...跑步:
fig = newLegend(fig = fig, newNames = {'Australia':'Australia = Dangerous', 'New Zealand' : 'New Zealand = Peaceful'})
...会给你:
我希望这就是您正在寻找的。如果没有,请随时告诉我!
完整代码:
import plotly.express as px
df = px.data.gapminder().query("continent == 'Oceania'")
fig = px.pie(df, values='pop', names='country')
fig.update_traces(textposition='inside')
fig.update_layout(uniformtext_minsize=12, uniformtext_mode='hide')
def newLegend(fig, newNames):
for item in newNames:
for i, elem in enumerate(fig.data[0].labels):
if elem == item:
fig.data[0].labels[i] = newNames[item]
return(fig)
fig = newLegend(fig = fig, newNames = {'Australia':'Australia = Dangerous',
'New Zealand' : 'New Zealand = Peaceful'})
fig.show()
编辑 1:来自 OP 的数据样本示例
您的数据面临的挑战是genders属于类型integer而不是类型string。因此,自定义函数尝试将一种类型的元素替换为另一种类型的元素。我通过一次性替换包含标签的整个数组来解决这个问题,而不是逐个元素地操作它。
阴谋:
完整代码:
import pandas as pd
import plotly.express as px
import numpy as np
# custom function to change labels
def newLegend(fig, newNames):
newLabels = []
for item in newNames:
for i, elem in enumerate(fig.data[0].labels):
if elem == item:
#fig.data[0].labels[i] = newNames[item]
newLabels.append(newNames[item])
fig.data[0].labels = np.array(newLabels)
return(fig)
'''
Pandas DataFrame:
'''
users_genders = pd.DataFrame({'0': {0: 1, 1: 2},
'802420': {0: 246049, 1: 106}})
users_genders = pd.DataFrame({'gender':[0,1,2],
'count_genders': [802420, 246049, 106]})
''' Pie Chart Viz '''
gender_distribution = px.pie(users_genders,
values='count_genders',
names='gender',
color_discrete_map={'0': 'blue',
'1': 'red',
'2': 'green'},
title='Gender Distribution <br>'
'between 2006-02-16 to 2014-02-20',
hole=0.35)
gender_distribution.update_traces(textposition='outside',
textinfo='percent+label',
marker=dict(line=dict(color='#000000',
width=4)),
pull=[0.05, 0, 0.03],
opacity=0.9,
# rotation=180
)
gender_distribution.update_layout(legend=dict({'traceorder': 'normal'}
# ticks='inside',
# tickvals=[0, 1, 2],
# ticktext=["0 - Female",
# "1 - Male",
# "2 - Undefined"],
# dtick=3
),
legend_title_text='User Genders')
# custom function set to work
gender_distribution=newLegend(gender_distribution, {0:"0 - Female",
1:"1 - Male",
2: "2 - Undefined"})
gender_distribution.show()
TA贡献1795条经验 获得超7个赞
newnames = {'0': 'zero', '1': 'one', '2': 'two'}
fig.for_each_trace(lambda t: t.update(
labels=[newnames[label] for label in t.labels]
)
添加回答
举报