在 plotly 中复制带有刻面和箭头注释的 ggplot2 图表

标签 r ggplot2 plotly ggplotly

我想在 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
)

所以现在 pl 看起来像这样: new image

与原始版本相似(实际上比原始版本更好):

original image

关于在 plotly 中复制带有刻面和箭头注释的 ggplot2 图表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59882529/

相关文章:

javascript - Plotly 中的多个 X 轴

R:计算数据集中每行值的数量并创建一个新列

r - 控制点阵密度图中绘图符号的 alpha 值

R - 将 ggplot 网格线放在前台

r - 自动缩放 Rmarkdown 文档中 ggplot2 的字体大小(等)

r - geom_bar(position = "dodge") 中条的宽度相同

r - 如何对由其他列定义的组内的列中的值进行索引?

r - 当外部程序通过 R 的 C API 接口(interface)调用 `Rf_allocXXX` 时,谁在管理内存?

python - 对 plotly 在线/离线/袖扣和不同版本感到困惑

python - 如何使用 seaborn 或 plotly 绘制时间序列图?