在ggplot中设置日期范围

use*_*980 13 r date ggplot2

我的数据框是z:

> dput(z)
structure(list(Month = structure(c(14975, 15095, 15156, 15187, 
15248), class = "Date"), Value = c(1, 1, 1, 6, 1)), .Names = c("Month", 
"Value"), row.names = c(NA, 5L), class = "data.frame")


ggplot(z, aes(Month, Value)) + 
    geom_bar(fill="orange",size=.3,  stat="identity", position="identity") +
    geom_smooth(data=z,aes(Month,Value,group=1), method="lm", size=2, color="navyblue") + 
    scale_x_date(breaks = "1 month", labels=date_format("%b-%Y"))
Run Code Online (Sandbox Code Playgroud)

这工作正常,但我真的很喜欢我的数据范围在2011年1月1日到2013年1月1日之间.我的示例日期是2011年1月1日至2011年1月10日.是否有一种简单的方法可以在ggplot中强制从2011年1月1日到2013年1月1日的日期范围?

jor*_*ran 30

该文档?scale_x_date提到它接受所有"典型的"连续规模论证,包括limits:

library(scales)
ggplot(z, aes(Month, Value)) + 
    geom_bar(fill="orange",size=.3,  stat="identity", position="identity") + 
    geom_smooth(data=z,aes(Month,Value,group=1), method="lm", size=2, color="navyblue") + 
    scale_x_date(date_breaks = "1 month", 
                 labels=date_format("%b-%Y"),
                 limits = as.Date(c('2011-01-01','2013-01-01')))
Run Code Online (Sandbox Code Playgroud)

  • 有用的答案,但缺少`库(scale)`调用生成`结构错误(list(call = match.call(),aesthetics = aesthetics,:找不到函数"date_format"`,这让我摸不着头脑一两分钟! (5认同)
  • 这段代码对我不起作用。也许 ggplot2 的重大更新打破了它。`错误:无效输入:date_trans 仅适用于 Date 类的对象`。 (2认同)
  • @Deleet 是的,看看你的要点,错误信息一点也不神秘。您的日期列实际上不是日期列。这是POSIXct。并且`date_trans` 尽职尽责地告诉你它只对`Date` 类的列有效。 (2认同)

42-*_*42- 7

对SO用户来说,除了'ggplot2'之外还要加载scales包,这是一种礼貌.有一个ggplot2::xlim功能,所以这工作:

  ...... + xlim(as.Date(c('1/1/2011', '1/1/2013'), format="%d/%m/%Y") )
Run Code Online (Sandbox Code Playgroud)

更新:因为一个无法解释的原因而得到了一个downvote.原始问题中的代码不再有效,但如果仅使用上面的xlim()调用替换scale_x_date(.)调用,则不会出现错误.

ggplot(z, aes(Month, Value)) + 
     geom_bar(fill="orange",size=.3,  stat="identity", position="identity") +
     geom_smooth(data=z,aes(Month,Value,group=1), method="lm", size=2, color="navyblue") + 
     xlim(as.Date(c('1/1/2011', '1/1/2013'), format="%d/%m/%Y") )
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

  • 此代码对我不起作用.也许ggplot2的重大更新打破了它.`错误:输入无效:date_trans只使用类Date的对象. (2认同)

Ric*_*gue 5

这是使用 ggplot 3.1 的解决方案,它需要对原始代码进行最少的调整:

ggplot(z, aes(Month, Value)) + 
    geom_bar(fill="orange",size=.3, stat="identity", position="identity") +
    geom_smooth(data=z,aes(Month,Value,group=1), method="lm", size=2, color="navyblue") + 
    scale_x_date(date_breaks = "1 month", 
           limits = as.Date(c('1/1/2011', '1/1/2013'), format="%d/%m/%Y"),
           date_labels="%b-%Y" ) +
    theme(axis.text.x = element_text(angle = 90))
Run Code Online (Sandbox Code Playgroud)

末尾的theme()是可选的,但如果您想使用原始"%b-%Y"格式字符串,则可以使格式更易于阅读。