AxW
AxW

Reputation: 662

Show the label for only a specific point in a Plotly graph?

For instance, with this example from the Plotly documentation

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()

enter image description here I'm searching for a way to show only the label for a specified point, say, only 'Peru' in this case.

Any help appreciated, thank you!

Upvotes: 2

Views: 2286

Answers (1)

vestland
vestland

Reputation: 61114

You can always edit the text attribute for fig.data[0] like this:

fig.data[0].text = [e if e == 'Peru' else '' for e in fig.data[0].text]

And get:

enter image description here

The downside here is that this will remove country names from the hoverlabel for all other countries:

enter image description here

So I would rather subset the data for the country you would like to highlight and use fig.add_annotation() like this:

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
                  )

And get:

enter image description here

Complete code:

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()

Upvotes: 4

Related Questions