我正在尝试在 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')
Run Code Online (Sandbox Code Playgroud)
小智 9
代码中的错误是您设置了 to 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()
Run Code Online (Sandbox Code Playgroud)
并返回了这样的图表:
| 归档时间: |
|
| 查看次数: |
15756 次 |
| 最近记录: |