如何更改ggplot中的默认日期间隔?

时间:2012-12-04 23:06:48

标签: r ggplot2

我不确定ggplot中的默认日期间隔是多少。我的数据有五个数据点,包括2011年9月,2011年12月,2012年3月,2012年6月和2012年9月。

ggplot显示我的数据中的不同数据点,我发现有点烦人。我错过了什么吗?

您能帮忙展示“2011年9月,2011年12月,2012年3月,2012年6月和2012年9月

x4.1.m<- structure(list(Var.1=structure(c(1L,2L,3L,4L,5L,6L,1L,2L,3L,4L,5L,6L,1L,2L,3L,4L,5L,6L,1L,2L,3L,4L,5L,6L,1L,2L,3L,4L,5L,6L),.Label=c("I'vechangedforwork/anewjob/goneonaworkplan","IwantaphonethatVodafonedoesn'toffer","IwantBestMates/Favourites","Iwasofferedorsawabetterofferonanothernetwork","Issueswiththe2degreesnetwork(poorcoverage)","Other"),class="factor"),YearQuarter=structure(c(1L,1L,1L,1L,1L,1L,2L,2L,2L,2L,2L,2L,3L,3L,3L,3L,3L,3L,4L,4L,4L,4L,4L,4L,5L,5L,5L,5L,5L,5L),.Label=c("2011-09-01","2011-12-01","2012-03-01","2012-06-01","2012-09-01"),class="factor"),value=c(0.23,0.23,0.121,0.25,0.223,0.14,0.39,0.22,0.05,0.37,0.25,0.2,0.09,0.14,0.05,0.3,0.4,0.12,0.13,0.1,0.26,0.38,0.28,0.15,0.33,0.05,0.06,0.44,0.32,0.43)),.Names=c("Var.1","YearQuarter","value"),row.names=c(NA,-30L),class="data.frame")

library(scales)
library(ggplot2)
###data 
x4.1.m$YearQuarter <- as.Date(x4.1.m$YearQuarter)
x4.1.m$label       <- paste(round(x4.1.m$value*100,0), "%", sep="")

### plot
x4.line <- ggplot(data=x4.1.m, aes(x=YearQuarter, y=value,colour=Var.1)) +
        geom_smooth(se=F, size=1.5)
x4.line <- x4.line + geom_text(aes(label = label),size = 3, hjust = 0.5, vjust =1.5) 

### theme  
x4.line <- x4.line +  theme(axis.line = element_line(colour = "black"),
       panel.grid.major = element_blank(),
       panel.background=element_blank(),
       panel.grid.minor = element_blank(),
       panel.border = element_blank()) 

x4.line <- x4.line +  ggtitle("Percentages:Main Reasons for Leaving Vodafone by Quarter") +
  theme(plot.title = element_text(size=rel(1.2)))+ 
scale_y_continuous(labels=percent, limits=c(0,0.5)) +
  scale_x_date(labels = date_format("%b-%y"),breaks = date_breaks("3 months"))+
  labs(y="Percentage",x="Year Quarter")

x4.line

1 个答案:

答案 0 :(得分:3)

你需要将breaks参数传递给scale_x_date(这里有一个惊喜。)

# your breaks 
d <- unique(x4.1.m[['YearQuarter']])
themestuff <-  theme(axis.line = element_line(colour = "black"),
                        panel.grid.major = element_blank(),
                        panel.background=element_blank(),
                        panel.grid.minor = element_blank(),
                        panel.border = element_blank())  

x4.line <- ggplot(data=x4.1.m, aes(x=YearQuarter, y=value,colour=Var.1)) +
 geom_smooth(se=F, size=1.5) + 
 geom_text(aes(label = label),size = 3, hjust = 0.5, vjust =1.5) +
 themestuff +  ggtitle("Percentages:Main Reasons for Leaving Vodafone by Quarter") +
 theme(plot.title = element_text(size=rel(1.2))) +
 scale_y_continuous(labels=percent, limits=c(0,0.5)) +
 scale_x_date(labels = date_format("%b-%y"), breaks = d)+
 labs(y="Percentage",x="Year Quarter")
x4.line

enter image description here