ggplotly与geom_ribbon分组

时间:2019-02-12 10:50:54

标签: r ggplot2 plotly ggplotly

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

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

以下是显示我根据此答案尝试的2种方法的代码: 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))

1 个答案:

答案 0 :(得分:1)

您好,这不是评论,而是答案,但我无权发表评论。

如果调查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

enter image description here