这里有一个ggplot2
方法来接近情节格式在你的问题:
library(ggplot2)
# Fake data
set.seed(1234)
nobs<-52
t<-seq(1,nobs)
x<-rnorm(nobs,0,10) + t + 20
dat = data.frame(year=rep(2004:2016, each=4), qtr=rep(1:4, 13), x = x)
ggplot(dat, aes(paste(year,qtr), x)) +
geom_vline(xintercept=seq(4.5,100,4), colour="grey80",lwd=0.3) +
geom_line(aes(group=1)) +
annotate(seq(2.5, 2.5 + 12*4, length.out=13), -2, label=2004:2016,
geom="text", colour="grey30", size=3.5) +
theme_bw(base_size=10) +
theme(axis.text.x=element_text(angl=-90, vjust=0.5, colour="grey30"),
panel.grid.major.x=element_blank()) +
scale_x_discrete(name="Quarter",
labels=rep(paste0(month.abb[seq(1,12,3)],"-",month.abb[seq(3,12,3)]),20)) +
coord_cartesian(xlim=c(0,13*4 + 1), ylim=c(-4,max(dat$x + 2)), expand=FALSE)
方面更接近您想要的格式,但在正常的ggplot工作流程内无法实现连接各个方面的线条(AFAIK)。在下面的图中,垂直线显示每个面之间的边界。 There are (somewhat complicated) ways尝试连接各个方面的线条,但我没有在下面的例子中做到这一点。
dat$qtr = rep(paste0(month.abb[seq(1,12,3)],"-",month.abb[seq(3,12,3)]),13)
dat$qtr = factor(dat$qtr, levels=paste0(month.abb[seq(1,12,3)],"-",month.abb[seq(3,12,3)]))
p=ggplot(dat, aes(qtr, x)) +
geom_line(aes(group=1)) +
coord_cartesian(xlim=c(0.5,4.5), expand=FALSE, ylim=c(-2,80)) +
facet_grid(. ~ year, switch="x") +
annotate(x=c(0.5, 4.5), xend=c(0.5,4.5), y=-16, yend=-2, geom="segment",
colour="grey70", size=0.3) +
theme_bw(base_size=10) +
theme(panel.margin=unit(0,"lines"),
axis.text.x=element_text(angl=-90, vjust=0.5, colour="grey30"),
panel.border=element_rect(colour="grey70", size=0.3),
panel.grid.major=element_blank(),
strip.background=element_rect(fill="grey90", colour="grey20"),
axis.line=element_line(colour="black")) +
labs(x="Quarter")
# Turn off clipping and draw plot
gt <- ggplot_gtable(ggplot_build(p))
gt$layout$clip[gt$layout$name=="panel"] <- "off"
grid.draw(gt)
什么是 “相同的格式” 是什么意思? – hrbrmstr
主要是x轴和y轴上的相同标签以及相同的图例位置。 –
那么,和回归线。我尝试了与abline函数类似的东西,但它不起作用。 –