2017-01-25 29 views
4

當ggplot使用極座標繪製線圖時,它會在最高和最低x值(下面的DecJan)之間留下間隙,而不是纏繞成螺旋線。我怎樣才能延續這條路線並縮小差距?極線ggplot圖中的連接間隙

特別是,我想使用月份作爲我的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

+0

[相關](http://stackoverflow.com/questions/41603341/spiral-barplot-using-ggplot-coord-polar-condegram/41610220#41610220)。 – Axeman

回答

4

這裏有一個有點 - 哈克選項:

# 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

顯然增加額外的數據點是不理想的,雖然如此,也許存在更優雅的答案。

+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

+0

請參閱[我的答案]的變體2(http://stackoverflow.com/a/41098075/3817004)。它將幾個月變成POSIXct並使用'scale_x_date()'。 – Uwe