【问题标题】:ggplot - get date label in Mon-yyyy formatggplot - 获取 Mon-yyyy 格式的日期标签
【发布时间】:2018-01-03 07:44:48
【问题描述】:

使用如下数据框

data = data.frame(
  name=rep(c('Toyota', "Honda", "Nissan") ,each=4)
  ,date=c(rep(seq(as.Date("2016/1/1"), by = "month", length.out = 4),2),rep(seq(as.Date("2017/1/1"), by = "month", length.out = 4),1)),
  sales=sample(10:20, 12, replace=T)
  )

我想绘制如下的销售折线图;

library(ggplot2)
ggplot(data, aes(x=date, y=sales)) + geom_line(aes(color=name))

这给了我 x 轴标签 2016-01 ... 2017-01 等等。

我需要将 x 轴标签设为 Jan-2016Feb-2016 等。

【问题讨论】:

  • 尝试添加类似+ scale_x_date(date_breaks = "1 month", date_labels = "%b-%Y")的内容?

标签: r ggplot2


【解决方案1】:

@Z.Lin 建议使用+ scale_x_date(date_breaks = "1 month", date_labels = "%b-%Y") 的评论完美地满足了您的要求。至少在您的样本数据中,您感兴趣的日期似乎有很大的未绘制间隙,这使得轴标签在当前形式中作为单个月份过于拥挤。 @Z.Lin 的解决方案的一个细微变化将休息时间更改为每两个月一次,并使用日期格式中的换行符代替破折号分隔符有助于提高可读性:

ggplot(data, aes(x=date, y=sales)) + 
  geom_line(aes(color=name))+
  scale_x_date(date_breaks = "2 month", date_labels = "%b\n%Y")+
  theme(axis.text.x = element_text(size = 8))

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-02-03
    • 2015-02-13
    • 2019-02-27
    • 1970-01-01
    • 2019-06-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多