1

I am working with a similar issue that have been discussed here: ggplot - connecting points in polar coordinates with a straight line and ggplot2: connecting points in polar coordinates with a straight line 2

I wanted straight line with coord_polar and the function coord_radar() from the ggiraphExtra package nearly got me where I wanted to be, i.e. (from a previous response see link 2 above)

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()

However, I would like to add background colour to this plot using annotate('rect') (or geom_rectangle); but when I do:

 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()

I get the following error message: Error in ``$<-.data.frame(*tmp*``, "r", value = numeric(0)) : replacement has 0 rows, data has 1

This error is a bit obscure to me, I'm not sure what to do with it. Note that the same code with coord_polar works just fine. See here: polar coord with coloured background

Any insights would be much appreciated. Apologies if this is resolved somewhere else, I'm pretty sure I've reviewed all the questions about this topic. Thank you

1 Answers1

0

I dunno where the error comes from and I guess it's not easy to debug. However, why not just use polygons:

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

lukeA
  • 53,097
  • 5
  • 97
  • 100