Attach the gap in the ggplot line graph

When ggplot creates a line graph with polar coordinates, it leaves a gap between the highest and smallest x values ​​( Decand Janbelow) instead of wrapping around in a spiral. How to continue the line and close this gap?

In particular, I want to use months as the x axis, but a graph of several years of data in one line of the cycle.

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 chart with spaces

+4
source share
1 answer

Here are some hacker options:

# 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 chart without spaces

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

+4
source

Source: https://habr.com/ru/post/1667708/


All Articles