简体   繁体   中英

plotly highlight line with dotted dash and marker with fig.update_traces

I am trying to make a line graph in Plotly, with a dotted and marked line. in this case I want the line that represents "Canada" to be dotted. I have figured out how to change the width and color but can't figure out how to make the line dotted. My original DF is much bigger, so go.scatter wouldn't be a solution for me. thanks for the help!

import plotly.express as px

# data
df = px.data.gapminder()
df = df[df['country'].isin(['Canada', 'USA', 'Norway', 'Sweden', 'Germany'])]

# plotly
fig = px.line(df, x='year', y='lifeExp',
              color='country')

# color "Canada" black and change the width of the line
fig.update_traces(patch={"line": {"color": "black", "width": 4}},#
                  selector={"legendgroup": "Canada"})

#i tried to extend the code with dash and mode, but do not work:
#fig.update_traces(patch={"line": {"color": "black", "width": 4, "dash": 'dot', "mode": 'lines+markers'}}, 

plotly.io.write_image(fig, file='testline.png', format='png')

I expect a dotted black line that will end up looking something like this. 在此处输入图像描述

The error in your code was that you were setting the mode to lines+markers , which is an invalid property in a line chart. The code that worked looks like this:

import plotly.express as px

# data
df = px.data.gapminder()
df = df[df['country'].isin(['Canada', 'USA', 'Norway', 'Sweden', 'Germany'])]

# plotly
fig = px.line(df, x='year', y='lifeExp',
              color='country')

fig.update_traces(patch={"line": {"color": "black", "width": 4}})
fig.update_traces(patch={"line": {"color": "black", "width": 4, "dash": 'dot'}}, selector={"legendgroup": "Canada"}) 

fig.show()

And returned a graph like this:

在此处输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM