我的数据框是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)
对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)
这是使用 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"格式字符串,则可以使格式更易于阅读。