我想在 plotly
中复制一个 ggplot2
图表,为此我尝试使用 ggplotly
函数。
图表如下 (p_arrow
):
library(data.table)
library(ggplot2)
library(plotly)
dset <- data.table(x = c(0, 1),
y = c(0, 1),
treatment = c(0, 1))
x_start <- dset[treatment == 0, x]
x_end <- dset[treatment == 1, x]
y_start <- dset[treatment == 0, y]
y_end <- dset[treatment == 1, y]
# base chart
p <- ggplot(dset, aes(x, y)) + geom_point() + facet_grid( ~ treatment)
# add annotations
p_arrow <- p + annotate(
"segment",
x = x_start,
xend = x_end,
y = y_start,
yend = y_end,
lty = 1,
size = 1,
arrow = arrow()
)
# chart to be replicated
p_arrow
# If I convert to plotly I lose the arrow
ggplotly(p_arrow)
plotly
版本没有箭头。这是 know issue因此,我一直在寻找一种直接在 plotly
中添加注释的方法。
第一次试验:
# my trials in ggplotly
pl <- ggplotly(p)
#pl1 only annotates the fist subplot
pl1 <- pl %>% add_annotations(
x = x_start,
y = y_start,
xref = "x",
yref = "y",
axref = "x",
ayref = "y",
text = "",
showarrow = TRUE,
ax = x_end,
ay = y_end,
arrowcolor = "black"
)
pl1
问题:第二个子图没有注释。
二审:
# add annotation in axis x2 and y2
pl2 <- pl1 %>% add_annotations(
x = x_start,
y = y_start,
xref = "x2",
yref = "y2",
axref = "x2",
ayref = "y2",
text = "",
showarrow = TRUE,
ax = x_end,
ay = y_end,
arrowcolor = "black"
)
pl2
问题:第二个子图中缺少点。
有没有办法复制 p_arrow
?
最佳答案
如果在对 add_annotations
的两次调用中将 yref
设置为同一轴(即 "y"
而不是 "y2"
),那么问题就解决了:
pl <- ggplotly(p)
pl <- pl %>% add_annotations(
x = x_end,
y = y_end,
xref = "x2",
yref = "y",
axref = "x2",
ayref = "y",
text = "",
showarrow = TRUE,
arrowhead = 3,
arrowsize = 2,
ax = x_start,
ay = y_start
) %>% add_annotations(
x = x_end,
y = y_end,
xref = "x",
yref = "y",
axref = "x",
ayref = "y",
text = "",
showarrow = TRUE,
arrowhead = 3,
arrowsize = 2,
ax = x_start,
ay = y_start
)
与原始版本相似(实际上比原始版本更好):
关于在 plotly 中复制带有刻面和箭头注释的 ggplot2 图表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59882529/