【问题标题】:Adjust time monthly time axis in ggplot2 to quarters?将ggplot2中的时间每月时间轴调整为季度?
【发布时间】:2018-02-17 13:54:42
【问题描述】:

我得到以下数据框:

          MONTH MINTEREST REGION    id
 <S3: yearmon>     <dbl>  <chr> <int>
1      Aug 2010    0.0443     NC     1
2      Sep 2010    0.0432     NC     2
3      Okt 2010    0.0422     NC     3
4      Nov 2010    0.0433     NC     4
5      Dez 2010    0.0475     NC     5
6      Jan 2011    0.0480     NC     6

我使用以下 ggplot2 代码来绘制框架:

ggplot(MINTEREST30, aes(x=MONTH, y=MINTEREST, group=REGION)) +
  geom_line(aes(color=REGION),size=1)+
  theme_bw()+
  theme(legend.position = c(0.8, 0.8)) +
  scale_color_manual(values = c("#86BC25","#0076A8","#BBBCBC","#E3E48D","#A0DCFF"))+
  scale_y_continuous(labels = scales::percent)+
  xlab("Months")+
  ylab("Mortgage Rate")

不幸的是,我得到了错误:

不知道如何为 yearmon 类型的对象自动选择比例。 默认为连续。

正如您在上面提供的图形中看到的那样,ggplot 将 x 轴自动设置为年份。由于我没有任何起点,因为我的数据是从 2010 年 8 月开始的。

我的问题是:是否有可能将轴调整为季度甚至月?

【问题讨论】:

  • 看看this link。我认为这是开始寻找解决方案的一种方式。

标签: r ggplot2


【解决方案1】:

如果p 是问题中ggplot 语句的值,请尝试以下方法之一:

p + scale_x_yearmon(format = "'%y/%m", n = 10)

p + scale_x_yearqtr(format = "%yQ%q", n = 10)

根据看起来不错的方式修改甚至省略格式和 n。根据问题中显示的数据,上述选择似乎没问题。对于 n 来说,任何足够大的数字都可以。欲了解更多信息,请参阅?scale_x_yearmon

【讨论】:

    【解决方案2】:

    jazzurro 让您走上了正确的道路。我试试类似的东西:

    scale_x_date(date_breaks = "3 months", date_labels = "%b-%y")
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-08-30
      • 1970-01-01
      • 2014-07-03
      • 2018-11-28
      • 1970-01-01
      • 1970-01-01
      • 2016-07-18
      • 2016-02-21
      相关资源
      最近更新 更多