您始终可以像这样编辑fig.data[0] 的text 属性:
fig.data[0].text = [e if e == 'Peru' else '' for e in fig.data[0].text]
得到:
这里的缺点是,这将从hoverlabel 中删除所有其他国家/地区的国家/地区名称:
因此,我宁愿将您想要突出显示的国家/地区的数据子集并使用fig.add_annotation(),如下所示:
df2 = df[df['country'] == 'Peru']
fig.add_annotation(x=np.log10(df2['gdpPercap']).iloc[0],
y=df2["lifeExp"].iloc[0],
text = df2["country"].iloc[0],
showarrow = True,
ax = 10,
ay = -25
)
得到:
完整代码:
import plotly.express as px
import numpy as np
df = px.data.gapminder().query("year==2007 and continent=='Americas'")
fig = px.scatter(df, x="gdpPercap", y="lifeExp",
# text="country",
log_x=True, size_max=60)
fig.update_traces(textposition='top center')
fig.update_layout(
height=800,
title_text='GDP and Life Expectancy (Americas, 2007)'
)
df2 = df[df['country'] == 'Peru']
fig.add_annotation(x=np.log10(df2['gdpPercap']).iloc[0],
y=df2["lifeExp"].iloc[0],
text = df2["country"].iloc[0],
showarrow = True,
ax = 10,
ay = -25
)
# f = fig.full_figure_for_development(warn=False)
fig.show()