如何填写geom_pointrange()后面的ggplot区域?

时间:2017-12-13 11:46:06

标签: r ggplot2 tidyverse


为什么在尝试填充其他geom背后的区域时会出现以下错误?

library(magrittr)
library(ggplot2)
library(ggstance)
#> 
#> Attaching package: 'ggstance'
#> The following objects are masked from 'package:ggplot2':
#> 
#>     geom_errorbarh, GeomErrorbarh

my_df <- structure(list(group = structure(1:2, .Label = c("group1", "group2"),
                                         class = "factor"), LL = c(-0.0265259354773537, 0.044689036850254),
                       stat = c(0.41037462410532, 0.516457204233787), UL = c(0.847275183687993, 
                                                         0.988225371617319)), row.names = c(NA, -2L), .Names = c("group", 
                                                                                                                 "LL", "stat", "UL"), class = c("tbl_df", "tbl", "data.frame"))

# Area to be filled in
rect1 <- data.frame(xmin = -0.2, xmax=0.45, ymin=-Inf, ymax=Inf) 

以下示例有效,但我希望rect1

后面有geom_pointrangeh
my_df %>% 
  ggplot() +
  geom_pointrangeh(aes(y = group, x = stat, xmin = LL, xmax = UL, 
                       color = group)) +
  geom_rect(data=rect1,aes(xmin=xmin,xmax=xmax,ymin=ymin,ymax=ymax),
            alpha=1,fill="grey70")

这个不起作用:

my_df %>% 
  ggplot() +
  geom_rect(data=rect1,aes(xmin=xmin,xmax=xmax,ymin=ymin,ymax=ymax),
            alpha=1,fill="grey70") +
  geom_pointrangeh(aes(y = group, x = stat, xmin = LL, xmax = UL))
#> Error: Discrete value supplied to continuous scale

PS:第一次使用reprex包在SO上发帖提问:非常好!

1 个答案:

答案 0 :(得分:3)

不要输入ggplot2(永远,真的)和&#34;黄金&#34; geom_blank()的尺度:

ggplot() +
  geom_blank(data=data, aes(stat, group)) +
  geom_rect(data=rect1, aes(xmin=xmin, xmax=xmax, ymin=ymin, ymax=ymax),
            alpha=1, fill="grey70")+
  geom_pointrangeh(data=data, 
                   aes(y = group, x = stat, xmin = LL, xmax = UL, color = group)) 

enter image description here

最好避免使用data作为变量名。