我想 for each 类别(LETTERS)绘制一个两条并排的条形图,并在每个条形图上添加一条水平线(y_ref为红线,z_ref为绿线).应该是这样的:

enter image description here

我try 了添加跟踪(以及添加线、添加段等),但找不到正确的方法.这是我到目前为止试过的一款reprex.

df <- tibble(x = LETTERS[1:5], y = runif(5), z = runif(5), y_ref = runif(5), z_ref = runif(5))

plot_ly(
  df,
  x = ~x,
  y = ~y,
  type = "bar",
  name = "a"
) %>% add_trace(
  y = ~z, 
  name = "b"
) %>% layout(
  legend = list(
    orientation = "h"
  )
) %>% add_trace(
  y = ~y_ref, 
  type = 'scatter', 
  mode = 'lines',
  marker = list(
    line = list(
      width = 2,
      color = "red"
    )
  )
) %>% add_trace(
  y = ~z_ref, 
  type = 'scatter', 
  mode = 'lines',
  marker = list(
    line = list(
      width = 2,
      color = "green"
    )
  )
)

编辑:我需要一个n条的解决方案.

推荐答案

在Plotly中,线段必须使用shapes.此外,由于x轴是离散的,因此形状的x将需要在paper空间中.

在图纸空间中工作时,使用plot domain计算x的值.Plotly将xy轴的默认值domain设置为[0,1].

横杆之间有间隙;这也必须考虑在内.我使用了三个函数来创建线段,使用了所有这些信息.

最后,我用seed表示重复性.

库、种子和底图

library(tidyverse)
library(plotly)

set.seed(8)
df <- tibble(x = LETTERS[1:5], y = runif(5), z = runif(5),
             y_ref = runif(5), z_ref = runif(5))

p = plot_ly(df, x = ~x, y = ~y,
        type = "bar", name = "a") %>% 
  add_trace(y = ~z, name = "b") 

创建片段

# standard shape elements, call for color
details <- function(col){
  list(type = 'line',
       line = list(color = col),
       xref = "paper", yref = "y")
}
# green lines for orange bars
segs = lapply(1:nrow(df),
              function(k){
                x1 <- (k + k)/10 - .02  # if the domain is [0, 1]
                x0 <- x1 - .08
                y0 <- y1 <- df[k, ]$z_ref
                line = list("x0" = x0, "x1" = x1,
                            "y0" = y0, "y1" = y1)
                deets = details("green")
                c(deets, line)
              })
# green lines for blue bars
segs2 = lapply(1:nrow(df),
               function(j){
                 x1 <- (j + j - 1)/10  # if the domain is [0, 1]
                 x0 <- x1 - .08
                 y0 <- y1 <- df[j, ]$y_ref
                 line = list("x0" = x0, "x1" = x1,
                             "y0" = y0, "y1" = y1)
                 deets = details("red")
                 c(deets, line)
               })
segs = append(segs, segs2)

把它放在一起

p %>% layout(legend = list(orientation = "h"),
             shapes = segs) 

enter image description here

R相关问答推荐

如何在geom_col中反转条

多个过滤器内的一个盒子在仪表板Quarto

R函数,用于生成伪随机二进制序列,其中同一数字在一行中不出现超过两次

传递ggplot2的变量作为函数参数—没有映射级别以正确填充美学

矩阵的堆叠条形图,条形图上有数字作为标签

如何根据数据帧中的值从该数据帧中提取值?

使用未知字符数(不受限制的最大长度)的Lookback有什么好的替代方案?

使用geom_iles在一个切片中包含多个值

使用shiny 中的所选要素行下拉菜单

为什么在写入CSV文件时Purrr::Pwalk不起作用

使用来自嵌套列和非嵌套列的输入的PURRR:MAP和dplyr::Mariate

按两个因素将观测值分组后计算单独的百分比

长/纬点继续在堪萨斯-SF结束,整齐的人口普查

R中的Desolve:返回的导数数错误

网络抓取NBA.com

识别部分重复行,其中一行为NA,其重复行为非NA

将日期列从字符转换为日期得到的结果是NAS

用从先前非NA值开始的递增序列替换NA值

我无法在geom_point的gglot中为不同的组定义调色板

如何更改曲线图图例中点和线的堆叠顺序