【发布时间】:2013-02-22 04:44:42
【问题描述】:
Please download the data here!
目标:像这样绘制图像:
特点: 1.两个不同的时间序列; 2. 下面板有一个反向的y轴; 3. 两个地块上的阴影。
可能的解决方案:
1. 刻面不合适 - (1) 不能只使一个刻面的 y 轴反转而保持其他刻面不变。 (2) 难以一一调整个别方面。
2. 使用视口排列单独的绘图,使用以下代码:
library(ggplot2)
library(grid)
library(gridExtra)
##Import data
df<- read.csv("D:\\R\\SF_Question.csv")
##Draw individual plots
#the lower panel
p1<- ggplot(df, aes(TIME1, VARIABLE1)) + geom_line() + scale_y_reverse() + labs(x="AGE") + scale_x_continuous(breaks = seq(1000,2000,200), limits = c(1000,2000))
#the upper panel
p2<- ggplot(df, aes(TIME2, V2)) + geom_line() + labs(x=NULL) + scale_x_continuous(breaks = seq(1000,2000,200), limits = c(1000,2000)) + theme(axis.text.x=element_blank())
##For the shadows
#shadow position
rects<- data.frame(x1=c(1100,1800),x2=c(1300,1850),y1=c(0,0),y2=c(100,100))
#make shadows clean (hide axis, ticks, labels, background and grids)
xquiet <- scale_x_continuous("", breaks = NULL)
yquiet <- scale_y_continuous("", breaks = NULL)
bgquiet<- theme(panel.background = element_rect(fill = "transparent", colour = NA))
plotquiet<- theme(plot.background = element_rect(fill = "transparent", colour = NA))
quiet <- list(xquiet, yquiet, bgquiet, plotquiet)
prects<- ggplot(rects,aes(xmin=x1,xmax=x2,ymin=y1,ymax=y2))+ geom_rect(alpha=0.1,fill="blue") + coord_cartesian(xlim = c(1000, 2000)) + quiet
##Arrange plots
pushViewport(viewport(layout = grid.layout(2, 1)))
vplayout <- function(x, y)
viewport(layout.pos.row = x, layout.pos.col = y)
#arrange time series
print(p2, vp = vplayout(1, 1))
print(p1, vp = vplayout(2, 1))
#arrange shadows
print(prects, vp=vplayout(1:2,1))
问题:
- x 轴未正确对齐;
- 阴影位置错误(因为 x 轴排列不正确)。
谷歌搜索后:
- 我首先注意到“来自 ggExtra 的 align.plots()”可以完成这项工作。但是,它已被作者弃用;
- 然后我尝试了gglayout solution,但没有运气 - 我什至无法安装“尖端”包;
-
最后,我使用以下代码尝试了gtable solution:
gp1<- ggplot_gtable(ggplot_build(p1)) gp2<- ggplot_gtable(ggplot_build(p2)) gprects<- ggplot_gtable(ggplot_build(prects)) maxWidth = unit.pmax(gp1$widths[2:3], gp2$widths[2:3], gprects$widths[2:3]) gp1$widths[2:3] <- maxWidth gp2$widths[2:3] <- maxWidth gprects$widths[2:3] <- maxWidth grid.arrange(gp2, gp1, gprects)
现在,上下面板的 x 轴确实对齐了。但影子位置仍然是错误的。更重要的是,我不能在两个时间序列上重叠阴影图。经过几天的尝试,我几乎放弃了……
有人可以帮帮我吗?
【问题讨论】:
-
这种类型的图你要经常做吗?在我看来,您发布的原件似乎只是有 MS Paint 或其他类似照片编辑软件的叠加层。
-
你可以把两张图放在一起,用
grid包覆盖矩形。 -
@Brandon:是的,作为一个古气候学专家,经常需要比较几个时间序列并在一个情节上标记有趣的部分。通常,我使用 Golden Software Grapher 来完成这项工作。这很耗时,因为您必须一次又一次地设置如此多的属性。这就是我尝试 R 的原因。@sebastian:非常感谢您提供图片,这真的很有帮助!而且我对 Grid 包不是很熟悉。不管怎样,我一定会试一试的。