以下代码提供了一种向 Plotly 图形添加两条迹线的方法:
import plotly.graph_objs as go
fig = go.Figure()
fig.add_trace(go.Scatter(
x = [0, 1, 2, 3], y = [1, 2, 3, 4],
mode = 'lines+markers',
name = "Trace 0",
))
fig.add_trace(go.Scatter(
x = [5,6,7,8], y = [1, 2, 3, 4],
mode = 'lines+markers',
name = "Trace 1",
))
fig.show()
Run Code Online (Sandbox Code Playgroud)
是否可以将这两条迹线合并为一条迹线,以便它们出现在图例中的同一标题下并共享相同的视觉属性(即颜色、标记等)?此外,合并这些跟踪应该可以在单击图例中的标题时切换可见性。
The other answer here is excellent, but I'll post an alternative solution for those interested. If for some reason you don't want to add another column to your dataframe (or maybe you're not using dataframes), you can specify the color of each trace and put your traces in the same legend group to ensure they toggle together.
This is also a bit closer to your original code syntax wise, but it is bit more of a workaround stylistically.
import plotly.graph_objs as go
fig = go.Figure()
trace_color = "#636EFA" ## default plotly blue
fig.add_trace(go.Scatter(
x = [0, 1, 2, 3], y = [1, 2, 3, 4],
mode = 'lines+markers',
name = "Trace 0",
marker = dict(color = trace_color),
showlegend = False,
legendgroup = "Trace",
))
fig.add_trace(go.Scatter(
x = [5,6,7,8], y = [1, 2, 3, 4],
mode = 'lines+markers',
name = "Trace",
marker = dict(color = trace_color),
legendgroup = "Trace",
))
fig.show()
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
967 次 |
| 最近记录: |