8

When ggplot makes a line plot with polar coordinates, it leaves a gap between the highest and lowest x-values (Dec and Jan below) instead of wrapping around into a spiral. How can I continue the line and close that gap?

In particular, I want to use months as my x-axis, but plot multiple years of data in one looping line.

Reprex:

library(ggplot2)

# three years of monthly data
df <- expand.grid(month = month.abb, year = 2014:2016)
df$value <- seq_along(df$year)

head(df)
##   month year value
## 1   Jan 2014     1
## 2   Feb 2014     2
## 3   Mar 2014     3
## 4   Apr 2014     4
## 5   May 2014     5
## 6   Jun 2014     6

ggplot(df, aes(month, value, group = year)) + 
    geom_line() + 
    coord_polar()

spiral plot with gaps

alistaire
  • 42,459
  • 4
  • 77
  • 117
  • [Related](http://stackoverflow.com/questions/41603341/spiral-barplot-using-ggplot-coord-polar-condegram/41610220#41610220). – Axeman Jan 25 '17 at 08:20

1 Answers1

5

Here's a somewhat-hacky option:

# make a data.frame of start values end values should continue to
bridges <- df[df$month == 'Jan',]
bridges$year <- bridges$year - 1    # adjust index to align with previous group
bridges$month <- NA    # set x value to any new value

       # combine extra points with original
ggplot(rbind(df, bridges), aes(month, value, group = year)) + 
    geom_line() + 
    # close gap by removing expansion; redefine breaks to get rid of "NA/Jan" label
    scale_x_discrete(expand = c(0,0), breaks = month.abb) + 
    coord_polar()

spiral plot without gaps

Obviously adding extra data points is not ideal, though, so maybe a more elegant answer exists.

alistaire
  • 42,459
  • 4
  • 77
  • 117
  • 1
    If you plot on a continuous scale it should become more obvious why extra data points are conceptually necessary: `ggplot(df, aes(as.integer(month), value, group = year)) + geom_line() + coord_polar() + scale_x_continuous(limits = c(0, 12))`. `geom_line` does not extrapolate. In my opinion it's a mistake that ggplot2 even plots this with a discrete scale. Note how it doesn't with cartesian coordinates. – Roland Jan 25 '17 at 07:32
  • Please, see Variant 2 of [my answer](http://stackoverflow.com/a/41098075/3817004). It turns months into POSIXct and uses `scale_x_date()`. – Uwe Jan 25 '17 at 08:24