R - ggplot2:coord_radar不使用geom_rect或annotate('rect')

时间:2017-05-25 10:04:43

标签: r ggplot2

我正在处理此处讨论过的类似问题: ggplot - connecting points in polar coordinates with a straight lineggplot2: connecting points in polar coordinates with a straight line 2

我希望与coord_polar成直线,coord_radar()包中的函数ggiraphExtra几乎让我想到的地方,即(来自之前的回复,请参阅上面的链接2)< / p>

iris %>% gather(dim, val, -Species) %>%
  group_by(dim, Species) %>% summarise(val = mean(val)) %>% 
  ggplot(aes(dim, val, group=Species, col=Species)) + 
  geom_line(size=2) + ggiraphExtra:::coord_radar()

但是,我想使用注释('rect')(或geom_rectangle)为此图添加背景颜色;但是当我这样做时:

 iris %>% gather(dim, val, -Species) %>%
    group_by(dim, Species) %>% summarise(val = mean(val)) %>% 
    ggplot(aes(dim, val, group=Species, col=Species)) + 
    geom_line(size=2) +
    annotate("rect", xmin=0, xmax =2.5 , ymin = -Inf, ymax = Inf, alpha=0.3, fill="#C77CFF")+
    annotate("rect", xmin=2.5, xmax =4.5 , ymin = -Inf, ymax = Inf, alpha=0.3, fill="#619CFF")+
    ggiraphExtra:::coord_radar()

我收到以下错误消息:     Error in ``$<-.data.frame*tmp*``, "r", value = numeric(0)) : replacement has 0 rows, data has 1

这个错误对我来说有点模糊,我不知道该怎么办。请注意,coord_polar的相同代码工作正常。看这里: polar coord with coloured background

任何见解都会非常感激。如果在其他地方解决这个问题,我很抱歉,我很确定我已经回顾了有关此主题的所有问题。 谢谢

1 个答案:

答案 0 :(得分:0)

我不知道错误来自哪里,我guess调试起来并不容易。但是,为什么不使用多边形:

p <- iris %>% gather(dim, val, -Species) %>%
    group_by(dim, Species) %>% summarise(val = mean(val)) %>%
    ggplot(aes(dim, val, group=Species, col=Species))
annotPolar <- list(
  annotate("rect",xmin=0, xmax =2.5 , ymin = -Inf, ymax = Inf, alpha=0.3, fill="#C77CFF"),
  annotate("rect",  xmin=2.5, xmax =4.5 , ymin = -Inf, ymax = Inf, alpha=0.3, fill="#619CFF"),
  coord_polar()
)

lst <- list(
   p + 
    geom_polygon(size=2, fill=NA, show.legend = F) +
    geom_line(size = NA) +
    guides(color = guide_legend(override.aes = list(size = 2))) + 
    annotPolar +
    ggtitle("polygon"),
  p + 
    geom_line(size=2) +
    annotPolar + 
    ggtitle("line"), 
  p + 
    geom_line(size=2) +
    ggiraphExtra:::coord_radar() +
    ggtitle("radar")
)
gridExtra::grid.arrange(grobs=lst, ncol = 2)

enter image description here