2015-02-23 68 views
1

scale_x_yearqtr我正在與所述數據集類似於下面的提取工作:R:設置限制,以在ggplot爲yearqtr(動物園)

head(nomis.lng.agg) 
    quarter decile   avg.val 
1 2004 Q4    1 5.680000 
2 2005 Q1    1 5.745763 
3 2005 Q2    1 5.503341 
4 2005 Q3    1 5.668224 
5 2005 Q4    1 5.244604 
6 2006 Q1    1 5.347222 

可變季度yearqtr類的由zoo作爲生成。剩下的兩列是數字。目前,我正在生成使用以下ggplot語法一個情節:

ggplot(data = subset(x = df, 
        subset = df$decile== 1 | 
         df$decile== 10), 
     aes(x = quarter, y = avg.val, group = decile)) + 
    geom_line(aes(linetype=as.factor(decile)), 
       size = 1) + 
    scale_x_yearqtr(format = "%YQ%q", n = 5) + 
    xlab("Quarter") + 
    ylab("Average val") + 
    ggtitle("Plot") + 
    scale_linetype_discrete(name="Legend") + 
    theme(panel.background = element_blank(), 
      axis.line = element_line(colour = "black"), 
      axis.text = element_text(size = 12, colour = "black"), 
      axis.title = element_text(size = 14, colour = "black"), 
      panel.grid.minor = element_blank(), 
      panel.grid.major.y = element_line(colour = "gray"), 
      panel.grid.major.x = element_blank(), 
      axis.text = element_text(size = 12, colour = "black"), 
      legend.text = element_text(size = 12), 
      legend.title = element_text(size = 12), 
      legend.key.width=unit(1.5,"cm"), 
      legend.position = "bottom", 
      legend.key = element_rect(fill = "white"), 
      legend.background = element_rect(colour = "black"), 
      plot.title = element_text(face="bold"), 
      plot.background = element_rect(colour = "black")) 

情節與x軸的異常幾乎是完美的。當前的x軸看起來像這樣: broken axis

我的重點是代碼scale_x_yearqtr(format = "%YQ%q", n = 5)。正如我的數據,從2004年Q4開始我不感興趣,密謀2004年Q1,但我想設置的限制:

scale_x_yearqtr(format = "%YQ%q", 
        limits=c(min(quarter), max=max(quarter))) 

然而,這並沒有產生預期的結果,儘管:

min(df$quarter) 
[1] "2004 Q4" 

回答

5

我想你剛剛沒有正確指定limits。此外,爲了更好地控制外觀,請使用breaks參數(而不是n)。

# some data 
df <- data.frame(x = as.yearqtr(2004 + seq(3, 8)/4), y = sample(1:6)) 

# setting limits only 
ggplot(data = df, aes(x, y, group = 1)) + 
    geom_line() + 
    scale_x_yearqtr(limits = c(min(df$x), max(df$x)), 
        format = "%YQ%q") 

enter image description here

# setting breaks 
ggplot(data = df, aes(x, y, group = 1)) + 
    geom_line() + 
    scale_x_yearqtr(breaks = seq(from = min(df$x), to = max(df$x), by = 0.25), 
        format = "%YQ%q") 

enter image description here