ターゲット: 次のような画像をプロットします。
特徴: 1. 2 つの異なる時系列。2. 下部パネルの y 軸は逆になっています。3. 2 つのプロットにまたがる影。
考えられる解決策:
1. ファセットは適切ではありません - (1) 1 つのファセットの y 軸を反転させ、他のファセットを変更しないようにすることはできません。(2) 個々の面を 1 つずつ調整するのは困難です。
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 ソリューションを試しましたが、うまくいきませんでした。「最先端」のパッケージをインストールすることさえできませんでした。
最後に、次のコードを使用し てgtable ソリューションを試しました。
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 軸が正しく整列します。しかし、影の位置はまだ間違っています。さらに重要なことに、2 つの時系列でシャドー プロットを重ねることはできません。数日間の試みの後、私はほとんどあきらめました...
誰か手を貸してくれませんか?