R:在yearqtr(动物园)的ggplot中设置scale_x_yearqtr的限制

时间:2015-02-23 16:57:28

标签: r ggplot2 time-series zoo as.date

我正在使用类似于以下摘录的数据集:

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

变量 quarter 属于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"

1 个答案:

答案 0 :(得分:10)

我认为您没有正确指定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