我有两个相当复杂的情节对象。对于两者,我需要为布局和字幕创建矩形。我有点困惑,发现在plotly
中没有这样的功能,例如在ggplot2
。
我可以想到两种如何创建这些矩形的方法:
将第一个解决方案和组与split
- 参数
library(plotly)
### 0. Create and order mock-data
data_line=data.frame(x=rep(1:2,2),y=rep(1:2,each=2))
data_fill=data.frame(x=rep(1:2,2),y=rep(0.5:1.5,each=2))
mydata=data.frame(x=rep(1:2,4),y=rep(c(1:2,0.5:1.5),each=2),
id=rep(letters[1:2],each=4))
mydata<-mydata[order(mydata$y,decreasing = TRUE),] # I tried if ordering helps
### 1. Solution using lines
plines<-function(){
p<-plot_ly() %>%
add_trace(data=data_line[data_line$y==2,],x=~x,y=~y,type='scatter',mode='lines',
split=~y,line=list(color='rgb(0,53,153)')) %>%
add_trace(data=data_fill[data_fill$y==1.5,],x=~x,y=~y,type='scatter',
mode='lines',split=~y,line=list(color='rgb(0,53,153)'),
fill = 'tonexty', fillcolor='rgb(0,53,152)') %>%
add_trace(data=data_line[data_line$y==1,],x=~x,y=~y,type='scatter',mode='lines',
split=~y,line=list(color='rgb(0,53,153)')) %>%
add_trace(data=data_fill[data_fill$y==0.5,],x=~x,y=~y,type='scatter',mode='lines',
split=~y,line=list(color='rgb(0,53,153)'),fill = 'tonexty',
fillcolor='rgb(0,53,152)')
return(p)
}
### 2. solution using layout options
playout<-function(){
p<-plot_ly() %>%
add_trace(data=data_line[data_line$y==2,],x=~x,y=~y,type='scatter',mode='lines',
split=~y,line=list(color='rgb(0,53,153)')) %>%
layout(shapes=list(list(type = "rect", fillcolor = 'rgb(0,53,153)',
line = list(color = 'rgb(0,53,153)'),
x0 = 1, x1 = 2, xref = "x",
y0 = 0.5, y1 = 1, yref = "y"),
list(type = "rect",fillcolor = 'rgb(0,53,153)',
line = list(color = 'rgb(0,53,153)'),
x0 = 1, x1 = 2, xref = "x",
y0 = 1.5, y1 = 2, yref = "y")))
return(p)
}
### 3. Solution: Grouping with split does not work
pwish<-function(){
p<-plot_ly() %>%
add_trace(data=mydata[mydata$id=='a',],x=~x,y=~y,type='scatter',mode='lines',
split=~y,line=list(color='rgb(0,53,153)')) %>%
add_trace(data=mydata[mydata$id=='b',],x=~x,y=~y,type='scatter',mode='lines',
split=~y,line=list(color='rgb(0,53,153)'),fill = 'tonexty',
fillcolor='rgb(0,53,152)')
return(p)
}
比较我使用的解决方案microbenchmark
:
microbenchmark::microbenchmark(plines(),playout(),pwish(),times=1000L)
Unit: milliseconds
expr min lq mean median uq max neval
plines() 7.294808 7.924909 10.064783 9.187790 11.836938 21.23335 1000
playout() 6.345640 6.911258 8.818893 7.600264 9.845335 18.80933 1000
pwish() 6.724504 7.316451 9.381053 7.990730 11.063591 25.15229 1000
基本上我对基准的解释有两个问题:
playout()
我没有想到的?
欢迎使用简单的HTML或Javascript解决方案。pwish()
无效的事实:playout()
更长的数据应该是最快的吗? pwish()
这样的解决方案(只有在您对2的回答为“不是&#39;”时才有意义)更新:
我现在用更大的模拟数据集再次运行microbenchmark
,而playout
大约需要同时,而pwish()
的使用时间增加了一点。因此,我现在非常确定playout()
是更有效的方法。