KansaiRobot
KansaiRobot

Reputation: 9912

In a Plotly Scatter plot , how do you join two set of points with a line?

I have the following code

import plotly.graph_objs as go
layout1= go.Layout(title=go.layout.Title(text="A graph",x=0.5),
        xaxis={'title':'x[m]'},
        yaxis={'title':'y[m]','range':[-10,10]})

point_plot=[
            go.Scatter(x=[3,4],y=[1,2],name="V0"),
            go.Scatter(x=[1,2],y=[1,1],name="V0"),
            go.Scatter(x=[5,6],y=[2,3],name="GT")
    ]
      
      
      
go.Figure(data=point_plot, layout=layout1).show()

which produces the following plot

enter image description here

However this is not what I want exactly. What I want is that the two sets marked with "V0" must be of the same color and have only one mark in the legend. (In fact I am going to plot much more than two sets, like 20 sets of pairs joined by a line and they all have to be the same color and have only one mark in the legend)

Upvotes: 6

Views: 9873

Answers (2)

rpanai
rpanai

Reputation: 13437

Here you should use the same legendgroup for the first to traces and set the same color manually. To hide the second legend the parameter is showlegend=False.

import plotly.graph_objs as go

line_color=dict(color="blue")

layout1= go.Layout(title=go.layout.Title(text="A graph",x=0.5),
        xaxis={'title':'x[m]'},
        yaxis={'title':'y[m]','range':[-10,10]})

point_plot=[
  go.Scatter(x=[3,4],
             y=[1,2],
             name="V0",
             legendgroup="V0",
             line=line_color),
  go.Scatter(x=[1,2],
             y=[1,1],
             name="V0",
             legendgroup="V0",
             line=line_color,
             showlegend=False),
  go.Scatter(x=[5,6],
             y=[2,3],
             name="GT")]
      
      
go.Figure(data=point_plot, layout=layout1).show()

enter image description here

Upvotes: 11

Reza
Reza

Reputation: 2025

You can combine two V0 segments in a single scatter and add an extra point with np.nan to split two segments value as follows:

import plotly.graph_objs as go
import numpy as np
layout1= go.Layout(title=go.layout.Title(text="A graph",x=0.5),
        xaxis={'title':'x[m]'},
        yaxis={'title':'y[m]','range':[-10,10]})

point_plot=[
            go.Scatter(x=[1,2,3,3,4],y=[1,1,np.nan, 1,2],name="V0"),
            go.Scatter(x=[5,6],y=[2,3],name="GT")
    ]
      
      
      
go.Figure(data=point_plot, layout=layout1).show()

Upvotes: 3

Related Questions