极坐标线 ggplot 图中的连接间隙

8
当ggplot使用极坐标制作线图时,它会在最高和最低x值之间留下一个缺口(如下面的DecJan),而不是绕成螺旋形。我该如何继续画这条线并关闭这个间隙?
特别地,我想将月份用作x轴,但在一个循环线中绘制多年的数据。
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


相关 - Axeman
1个回答

5

这里有一个有点“hacky”的选项:

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

显然,添加额外的数据点并不理想,因此可能存在更优雅的解决方案。

没有间隙的螺旋图


1
如果您在连续比例上绘制,就会更明显地看出为什么概念上需要额外的数据点:ggplot(df, aes(as.integer(month), value, group = year)) + geom_line() + coord_polar() + scale_x_continuous(limits = c(0, 12))geom_line不会外推。在我看来,ggplot2即使使用离散比例绘制也是一个错误。请注意,它在笛卡尔坐标系下不会这样做。 - Roland
请参考我的答案的第二种方法。它将月份转换为POSIXct格式,并使用scale_x_date()函数。 - Uwe

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接