Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
275 views
in Technique[技术] by (71.8m points)

R: Remove line connecting first and last point in plotly

I am using R, package plotly and I have problem with connecting first and last point in my graph. I want to avoid it. The code is following:

graph<-plot_ly(data, x = ~date, y = ~variable, z = ~value, mode="lines")

I tried google some solution, but nothing work so far.

The graph looks like this.

Can anyone help?

question from:https://stackoverflow.com/questions/66067215/r-remove-line-connecting-first-and-last-point-in-plotly

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

If I understand correctly, you don't want the lines in variables 1, 2, 3... to be connected to each other, right?

If this is the case, I think what is happening is that plotly is assuming all your data belongs to the same series.

You need to tell it that the data from each variable is a different series. You can do it by mapping the variable to an attribute of the line (color, linetype, stroke, etc...).

library(tidyverse)
library(plotly)

# Create a data set from EuStockMarkets data for this example
# (this is just to put the data in a dataframe in the same format as your dataset. You can skip this part)
df.data <- EuStockMarkets %>% as.data.frame() %>% 
  dplyr::mutate(date=time(EuStockMarkets)) %>% 
  dplyr::mutate(year=as.integer(floor(date))) %>%
  dplyr::mutate(day.of.year = ceiling((date-year) * 365)) %>%
  dplyr::mutate(date=ymd(sprintf('%4d-01-01', year))+ days(day.of.year)) %>%
  dplyr::select(-year, -day.of.year) %>%
  tidyr::pivot_longer(-date, names_to = "variable") %>%
  dplyr::arrange(variable, date)

plot_ly(data=df.data, x = ~date, y = ~variable, z = ~value, type="scatter3d", mode='lines', color = ~variable)

enter image description here

If you don't want the lines in each variable to have different colors, you can use the split argument, which will create a different trace (i.e., line) for each value of variable. I had to set the color of the line manually otherwise plotly set a different color automatically. I also removed the legend.

plot_ly(data=df.data, x = ~date, y = ~variable, z = ~value, type="scatter3d", mode='lines', split=~variable, color=I('black')) %>% layout(showlegend = FALSE)

enter image description here


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...