有一条线穿过它们的子图

Subplots with a line passing through them

我需要通过 plotly 中的一堆小提琴情节。所以我想出了这段代码。

cd = data.frame(id = 1:100, norm = rnorm(100), poi = rpois(100, 1), exp 
= rexp(100,1))
cd = melt(cd, id= "id")
p1 = plot_ly(cd, x=~variable, y=~value, type = 'violin', box = 
list(visible =T), meanline = list(visible = T))%>%
layout(annotations = list(text = sprintf("Seeds=10, Coupons=5", 1:10), 
font = list(size=16), xanchor = "center", xref = "paper", yref = 
"paper", yanchor = "top", showarrow = F, y =1, x=0.5))

ad = data.frame(id = 1:100, norm = rnorm(100), poi = rpois(100, 1), exp 
= rexp(100,1))
ad = melt(ad, id= "id")
p2 = plot_ly(ad, x=~variable, y=~value, type = 'violin', box = 
list(visible =T), meanline = list(visible = T))%>%
layout(annotations = list(text = sprintf("Seeds=20, Coupons=5", 1:10), 
font = list(size=16), xanchor = "center", xref = "paper", yref = 
"paper", yanchor = "top", showarrow = F, y =1, x=0.5))
subplot(p1,p2, shareY = T)

它给了我这个情节

但我希望看到一条穿过 1.8 的公共线切割所有地块

还将'trace 0'替换为'cd',将'trace 1'替换为'ad' 谢谢

您可以在每个图中使用 add_lines 添加一条水平线,并通过设置名称 = 'cd' 或 'ad' 来标记图例:

library(reshape2)
library(dplyr)
library(plotly)
cd = data.frame(id = 1:100, norm = rnorm(100), poi = rpois(100, 1), exp = rexp(100,1))
cd = melt(cd, id= "id")
p1 = plot_ly(cd, x=~variable, y=~value, type = 'violin',name = 'cd', box = 
list(visible =T), meanline = list(visible = T))%>% add_lines(x = ~variable, y =
rep(1.8,length(cd$id)),showlegend=FALSE)%>%
layout(annotations = list(text = sprintf("Seeds=10, Coupons=5", 1:10), 
font = list(size=16), xanchor = "center", xref = "paper", yref = 
"paper", yanchor = "top", showarrow = F, y =1, x=0.5))

ad = data.frame(id = 1:100, norm = rnorm(100), poi = rpois(100, 1), exp = 
rexp(100,1))
ad = melt(ad, id= "id")
p2 = plot_ly(ad, x=~variable, y=~value, type = 'violin',name = 'ad',box =
list(visible =T), meanline = list(visible = T))%>% add_lines(x = ~variable, y =
rep(1.8,length(ad$id)),showlegend=FALSE)%>%
layout(annotations = list(text = sprintf("Seeds=20, Coupons=5", 1:10), 
font = list(size=16), xanchor = "center", xref = "paper", yref = 
"paper", yanchor = "top", showarrow = F, y =1, x=0.5))

vline <- function(x = 0, color = "red") {
list(
type = "line", 
y0 = 0, 
y1 = 1, 
yref = "paper",
x0 = x, 
x1 = x, 
line = list(color = color)
  )
}

subplot(p1,p2, shareY = T)