简体   繁体   中英

R - Add trace in Plotly if condition is met

I am creating a scatter plot graph and I would like the points connected by a trace if a condition is met. My data is separated into sequences, if an X and Y coordinate is part of the same sequence, I would like there to be a trace. My sample data and code snippet is below.

Sample Data:

X   Y   Seq
1   3    1
2   5    1
1   4    1
3   1    2
4   5    2
6   3    3
3   4    3

In this example I would like points (1, 3), (2, 5), (1, 4) traced, points (3, 1), (4, 5) traced, and points (6, 3), (3, 4) traced. There should be a break in the trace if a new sequence starts.

Code:

 plot_ly (data, x = data$X , y = data$Y,
          type = "scatter", 
          mode="markers")%>%
          add_trace(data$Seq==shift(data$Seq, type="lag"), mode="lines")

Here is an image of the plot that my actual data is giving me. You can see the points are being plotted but there is no break. 跟踪

The problem lies in your use of add_trace . You're passing what I assume is a subset of your data to the first argument of add_trace when this argument expects an existing plot/trace. The problem is, since you're piping in with %>% the function is inheriting the original data and ignoring your subset.

Note that the below will give the same plot even though my variable NO has nothing to do with the plot:

X=c(1,2,1,3,4,6,3)
Y=c(3,5,4,1,5,3,4)
seq=c(1,1,1,2,2,3,3)
dataX <- data.frame(X,Y,seq)

NO <- "this won't work"
plot_ly plot_ly (dataX, x = dataX$X , y = dataX$Y,
         type = "scatter", 
         mode="markers") %>%
          add_trace(NO, mode="lines")

在此处输入图片说明

You can fix this with inherit=F , but then it won't work because add_trace is trying to add something to the plot NO which isn't a plot (and your subset wouldn't work either)

plot_ly (dataX, x = dataX$X , y = dataX$Y,
         type = "scatter", 
         mode="markers") %>%
  add_trace(NO, mode="lines", inherit=FALSE)

## No trace type specified: 

When you add traces you want to be explicit in the x= and y= . Then you can allow it to automatically inherit the previous plot/trace, or specify one. As for what you're trying to do, you could build it up with a loop:

#make the plot
p <- plot_ly (dataX, x = dataX$X , y = dataX$Y,
         type = "scatter", 
         mode="markers")

#build it up
for(i in levels(factor(dataX$seq))){
  #subset data
  dataFilt <- dataX[dataX$seq==i,]
  #add it
  p <- add_trace(p, x=dataFilt$X, y=dataFilt$Y,mode="lines",color ='yellow')
}
p

在此处输入图片说明

This makes a new series each time so it's a bit of a work around. You can hide the legend and it looks correct:

p %>%
  layout(showlegend = FALSE)

在此处输入图片说明

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