Цель: Настроить изображение следующим образом:
Особенности: 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).
После разыгрывания всего:
- Сначала я заметил, что "align.plots() из ggExtra" может выполнять эту работу. Однако автор устарел от усталости;
- Затем я попробовал решение gglayout, но не повезло - я даже не смог установить "передовой" пакет;
-
Наконец, я пробовал 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 верхней и нижней панели правильно выровнена. Но теневые позиции по-прежнему ошибочны. И что еще более важно, я не могу наложить теневой сюжет на два временных ряда. После нескольких попыток дня я чуть не сдался...
Может ли кто-нибудь здесь дать мне руку?