Search code examples
rggplot2polar-coordinates

Ggplot2: coord_polar() with geom_col()


I have an issue when using coord_polar() together with geom_col(). I have degree values ranging from 0 to <360. Let's say there are in steps of 20, so 0, 20, 40... 340. If I plot them with coord_polar() I have two issues:

  • values 0 and 340 touch each other and don't have the same gap as the other columns
  • the "x-axis" is offset slightly, so that 0 does not point "north"

See this minimal example.



suppressWarnings(library(ggplot2))


df <- data.frame(x = seq(0,359,20),y = 1)

ninety = c(0,90,180,270)

p <- ggplot(df, aes(x,y)) +
  geom_col(colour = "black",fill = "grey") +
  geom_label(aes(label = x)) + 
  scale_x_continuous(breaks = ninety) +
  geom_vline(xintercept = ninety, colour = "red") +
  coord_polar()

p

If I set the x-axis limits, the rotation of the coordinate system is correct, but the column at 0 disappears due to lack of space.


p+scale_x_continuous(breaks = c(0,90,180,270),limits = c(0,360))
#> Scale for 'x' is already present. Adding another scale for 'x', which
#> will replace the existing scale.
#> Warning: Removed 1 rows containing missing values (geom_col).

Created on 2019-05-15 by the reprex package (v0.2.1)


Solution

  • Since the space occupied by each bar is 20 degrees, you can shift things by half of that in both scales and coordinates:

    ggplot(df, aes(x,y)) +
      geom_col(colour = "black",fill = "grey") +
      geom_label(aes(label = x)) + 
      scale_x_continuous(breaks = ninety,
                         limits = c(-10, 350)) + # shift limits by 10 degrees
      geom_vline(xintercept = ninety, colour = "red") +
      coord_polar(start = -10/360*2*pi) # offset by 10 degrees (converted to radians)
    

    plot