How can I get the following code to draw a line between (1,2) and (3,2)?
plot_ly(x=c(1,2,3),
y=c(1,2,3),
type='scatter',
mode='markers',
color=as.factor(c('a','b','c')))%>%
add_trace(x=c(1,3,NA),
y=c(2,2,NA),
mode='lines')
The solution here R plotly add_trace to a chart with color groups doesn't work. Thanks.
Edit: Using inherit=FALSE
does the job (thanks Jonny Phelps)
plot_ly(x=c(1,2,3),
y=c(1,2,3),
type='scatter',
mode='markers',
color=as.factor(c('a','b','c')))%>%
add_trace(x=c(1,3),
y=c(2,2),
mode='lines',
inherit = FALSE,
line=list(color='black'))
Answering from your comment. I have some real pain with Plotly sometimes. This sort of works, but the legend is a mess, and will need some work.
The challenge is making multiple coloured lines from one series. I don't think Plotly handles these natively (would love to see a better example). Therefore I've just looped it. You might be able to get something more elegant with the group=
option.
I added a 4th value in as it shows output better.
edit: I have a real pain point with the colour of "a". If you look at the first p, it is green. After the loop, it becomes brown. That's why I added "lines+markers", instead of "markers". Someone will know how to improve this, but its another Plotly pain
library(plotly)
library(RColorBrewer)
dat <- data.frame(x1=c(1,2,3,4), y1=c(1,2,3,4), mycolor=c('a','b','c','d'),
x2=c(1,2,3,NA), y2=c(1,2,3,NA),
stringsAsFactors = FALSE)
colours <- brewer.pal(length(unique(dat$mycolor)), "Dark2")
p <- plot_ly(data=dat, x=~x1, y=~y1, colors=colours) %>%
add_trace(mode='markers', color=~mycolor, data=dat,
x=~x1, y=~y1)
p
N <- nrow(dat)-1
for(i in 1:N){
p <- p %>% add_trace(data=dat[i:(i+1),], x=~x2, y=~y2, mode='lines+markers',
type="scatter", color=colours[i],
inherit=FALSE)
}
p
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.