gpt4 book ai didi

python - 用 fig.update_traces 用虚线和标记突出显示线

转载 作者:行者123 更新时间:2023-12-02 18:48:49 26 4
gpt4 key购买 nike

我正在尝试在 Plotly 中制作一个折线图,带有虚线和标记线。在这种情况下,我希望代表“加拿大”的线被点缀。我已经想出如何更改宽度和颜色,但无法弄清楚如何使线条变成虚线。我原来的 DF 大得多,所以 go.scatter 对我来说不是一个解决方案。感谢您的帮助!

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

我希望一条黑色虚线最终看起来像这样。 enter image description here

最佳答案

您的代码中的错误是您将 mode 设置为 lines+markers,这是折线图中的无效属性。有效的代码如下所示:

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

并返回了这样的图表:

enter image description here

关于python - 用 fig.update_traces 用虚线和标记突出显示线,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67064045/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com