绘制只有一条彩色线条的多线图表

Plotly multi-line charts with only one line colored

如何制作交互式多线图,其中只有一条感兴趣的线是彩色的,而其他线都是灰色的:

所以在这里,我希望美国是红色的,而其他国家是灰色的。这是我目前所拥有的:

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

但它只改变悬停颜色,不改变线条颜色

我尝试将美国单独绘制为自己的图形,然后将其更新为原始图形,但效果不佳。

您始终可以直接使用 for 循环编辑 fig 的元素以获得此:

完整代码:

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