【问题标题】:ggplotly with geom_ribbon groupingggplotly 与 geom_ribbon 分组
【发布时间】:2019-07-05 23:59:52
【问题描述】:

我在将 ggplot 转换为 plotly 对象并保留相同的图例属性时遇到了一些问题。我想要什么:

  • 对于分组系列,单行表示适合,褪色区域表示相同颜色的丝带,具有透明度
  • 色带边缘没有线条
  • 线条、点和丝带的分组图例

这是显示我根据此答案尝试的两种方法的代码: ggplot: remove lines at ribbon edges

正如您在运行时看到的那样,两者都有不良影响。任何建议都会很棒:)

library(plotly)
library(ggplot2)
# fake data
set.seed(1)
dt <- data.frame(x=rep(1:7,2), group=rep(letters[1:2], each=7), value=runif(14))
dt$lwr <- dt$value*.9
dt$upr <- dt$value*1.1

# build plot in ggplot, don't want lines at the edge
pl <- ggplot(data=dt, aes(y=value, x=x, group=group, colour=group,
                          fill=group)) +
  geom_point() +
  geom_line() +
  geom_ribbon(aes(ymin=lwr, ymax=upr), alpha=.3, linetype=0) +
  theme_minimal()

# looks ok, no lines at the edges
pl

# lines at edges, single group
ggplotly(pl)

# alternative: try reverting colour to NA
pl2 <- ggplot(data=dt, aes(y=value, x=x, group=group, colour=group,
                          fill=group)) +
  geom_point() +
  geom_line() +
  geom_ribbon(aes(ymin=lwr, ymax=upr), alpha=.3, colour=NA) +
  theme_minimal()

# looks ok
pl2

# no lines, but now not grouped, and some weird naming
ggplotly(pl2)

谢谢,乔尼

编辑: 除了接受的答案,以函数形式

# dd: ggplotly object
library(stringi)
library(rvest)
remove_ggplotly_ribbon_lines <- function(dd){
  find <- rvest::pluck(dd$x$data, "fillcolor")
  w <- which(!sapply(find, is.null))
  for(i in w){
    dd$x$data[[i]]$line$color <- 
      stringi::stri_replace_all_regex(dd$x$data[[i]]$line$color, ",[\\d.]*\\)$", ",0.0)")
  }
  return(dd)
}
remove_ggplotly_ribbon_lines(ggplotly(pl))

【问题讨论】:

    标签: r ggplot2 plotly ggplotly


    【解决方案1】:

    嗨,这更像是评论而不是答案,但我无权发布 cmets。

    如果您调查 ggplotly 对象,您会发现它实际上只是一个列表。更改列表的正确元素有助于控制绘图选项。

    下面的解决方案只是改变了色带边缘线条的 alpha。希望这会有所帮助

    library(plotly)
    
    set.seed(1)
    dt <- data.frame(x=rep(1:7,2), group=rep(letters[1:2], each=7), value=runif(14))
    dt$lwr <- dt$value*.9
    dt$upr <- dt$value*1.1
    
    # build plot in ggplot, don't want lines at the edge
    pl <- ggplot(data=dt, aes(y=value, x=x, group=group, colour=group,
                          fill=group)) +
    geom_point() +
    geom_line() +
    geom_ribbon(aes(ymin=lwr, ymax=upr), alpha=.3, linetype=0) +
    theme_minimal()
    
    # looks ok, no lines at the edges
    pl
    
    # no lines at edges
    dd = ggplotly(pl)
    dd$x$data[[3]]$line$color = "rgba(248,118,109,0.0)"
    dd$x$data[[4]]$line$color = "rgba(0,191,196,0.0)"
    dd
    

    【讨论】:

    • 谢谢,我想我可以通过提取列表中的一些元素来找到一种使 3、4 数字自适应的方法
    • 编辑原始问题以功能形式添加您的答案供参考
    猜你喜欢
    • 2019-03-19
    • 2020-01-31
    • 1970-01-01
    • 1970-01-01
    • 2019-11-29
    • 1970-01-01
    • 2021-10-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多