【问题标题】:Show the label for only a specific point in a Plotly graph?仅在 Plotly 图中显示特定点的标签?
【发布时间】:2021-08-02 04:00:57
【问题描述】:

例如,使用 Plotly 文档中的这个示例

import plotly.express as px

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)'
)
fig.show()

我正在寻找一种只显示指定点的标签的方法,比如在这种情况下只显示“秘鲁”。

任何帮助表示赞赏,谢谢!

【问题讨论】:

  • 我的建议对您有何帮助?

标签: python graph plotly


【解决方案1】:

您始终可以像这样编辑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()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-03-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-05-13
    相关资源
    最近更新 更多