Plotly multi-line charts with only one line colored

Viewed 1037

How do I make an interactive multi line chart where only one line of interest is colored whereas the other lines are all greyed out:

So here, I want US to be colored Red but the other countries grey. This is what I have so far:

import pandas as pd
import plotly.express as px

df = px.data.gapminder()
fig = px.line(df, x='year', y='pop', color="country", hover_name="country",color_discrete_map={'United States': 'Red'})
fig.update_layout(autosize=False,width=700,height=500)
fig.show()

But it only changes the hover color, not the line color

I tried plotting US separately as its own figure and then updating it to the original figure but it does not work as well.

1 Answers

You can always edit the elements of your fig directly using a for loop to get this:

enter image description here

Complete code:

import pandas as od
import plotly.express as px

df = px.data.gapminder()
fig = px.line(df, x='year', y='pop', color="country", hover_name="country")

# edit colors
for d in fig['data']:
    if d['name'] == 'United States':
        d['line']['color']='red'
    else:
        d['line']['color']='lightgrey'

fig.show()
Related