R

时间:2016-06-15 18:27:14

标签: r plotly

我试图在plotly中为多行设置线型(" solid"," dash"," dot"等)。我的数据框中有一个列(因子变量),它指定了行的类型。

以下是我正在使用的示例代码。

mydf <- data.frame(x = c(1:10), y1 = c(11:20), y2 = c(21:30))
mydf1 <- gather(mydf,'var', 'val', -x)
mydf1$lt <- factor(c(rep("solid",10),rep("dot",10)))
pal <- RColorBrewer::brewer.pal(nlevels(mydf1$lt),"Set1")
p <-plot_ly(mydf1, x = x, y = val, type = 'line', color = var,colors = pal,line = list(width = 3, dash = lt))
p<- layout(p,title = "Hello", annotations = list(x = mydf1$x, y = mydf1$var))

p   

mydf1 $ lt指定所需的线型。 对于上面的例子,y1必须是实线,y2必须是虚线。

enter image description here

我可以通过使用add_trace()单独添加行来解决问题。我正在寻找一种更简洁,更优雅的方式来做同样的事情。以下是一种可能的解决方案。

p1 <- plot_ly(mydf)
p1 <- add_trace(p1, x = x, y = y1, line = list(dash = "dash"))
p1 <- add_trace(p1, x = x, y = y2, line = list(dash = "solid"))
p1

enter image description here

1 个答案:

答案 0 :(得分:0)

  

对于上面的例子,y1必须是实线,y2必须是点   线。

你可以做到

A

library(ggplot2) library(tidyr) library(plotly) mydf <- data.frame(x = c(1:10), y1 = c(11:20), y2 = c(21:30)) mydf1 <- gather(mydf,'var', 'val', -x) mydf1$lt <- factor(c(rep("solid",10),rep("dot",10))) pal <- RColorBrewer::brewer.pal(nlevels(mydf1$lt),"Set1") p <-plot_ly( transform(mydf1, lt=c(solid="solid", dot="3")[lt]), x = x, y = val, type = 'line', color = var, colors = pal, line = list(dash = lt) ) p <- layout( p, title = "Hello", annotations = list(x = mydf1$x, y = mydf1$var) ) p 如果你想要反过来的话。

enter image description here