2017-02-20 5 views
0

は私の次のstackoverflowポストに答えるDWWている2つのggplot2のプロットを整列させる:どのように背景画像

how to fit the plot over a background image in R and ggplot2

は、私はなりたい、ほぼどこに私は非常に近いです。ただし、前のプロットで描画されたプロットを結合すると、背景画像のプロットはプロットパネル領域にブリードしますが、他のプロットはプロットパネル領域に入りません。 enter image description here

最初のプロットの上部にあるパネルスペースと、右側の背景イメージを持つプロットの画像がプロットパネルエリアを埋めるように拡大されている様子を参照してください。背景イメージを削除すると、両方のプロットが完全に整列します。私は上と下の両方でパネル領域を拡張したり塗りつぶしたりしないように背景イメージを制限しようとしています。私はそれを行う方法がわかりません。サンプルコードを以下に示します。

ibrary(ggplot2) 
library(readxl) 
library(jpeg) 
library(grid) 

df_ct <- data.frame(X0 = 0:100) 
df_ct$X1 = sin(df_ct$X0) +rnorm(101) 

setwd('~/R/Image_Example') 
image_file <- "C1_9195-9197.jpg" 
img <- readJPEG(image_file) 

g_hra <-ggplot(df_hra_plot_current) + geom_point(aes(x,y),size=0,color='white') + 
    geom_rect(data=hra_rect,inherit.aes=FALSE, aes(xmin=xmin,xmax=xmax,ymin=ymin,ymax=ymax,group=id,fill=factor(tier))) + 
    scale_fill_manual(values = hra_color_vector) + guides(fill=FALSE) + 
    scale_y_reverse() + ylab("Depth") + 
    theme(axis.title.x=element_blank(), axis.text.x=element_blank(), axis.ticks.x=element_blank(), 
    axis.title.y=element_blank(), axis.text.y=element_blank()) + 
    theme(plot.margin = unit(c(0,0,0,0), "lines")) 

g <- rasterGrob(img, width=unit(1,"npc"), height=unit(1,"npc"), interpolate = FALSE) 

g_ct <- ggplot(data=df_ct) + 
    annotation_custom(g, -Inf, Inf, -Inf, Inf) + 
    geom_path(aes_string(x=df_ct$X1, y=df_ct$X0), color='cyan') + 
    scale_y_reverse("") + 
    theme(plot.margin = unit(c(0,0,0,0), "lines"), 
     axis.line.x = element_blank(), 
     axis.ticks.x = element_blank(), 
     axis.text.x = element_blank(), 
     axis.line.y = element_blank()) + 
    scale_x_continuous("") 

grid.arrange(g_hra, g_ct, ncol = 2) 

答えて

0

これは私がどのような種類の作品を見つけたかです。それはそれを処理するための最良の方法であるかどうかは知りませんが、プロットの両方で、私はscale_y_reverseと、以下に示すscale_x_continuousなどの両方の中=のC(0,0)を展開置く:

g_ct <- ggplot(data=df_ct_current) + 
    annotation_custom(g, xmin=-Inf, xmax=Inf, ymin=-Inf, ymax=Inf) + 
    geom_path(aes_string(x=df_ct_current$X1, y=df_ct_current$X0), color='cyan') + 
    scale_y_reverse(expand = c(0,0)) + 
    scale_x_continuous("", expand = c(0,0)) + 
    theme(axis.title.y=element_blank(), axis.text.y=element_blank(), axis.ticks.y=element_blank()) + 
    theme(axis.title.x=element_blank(), axis.text.x=element_blank(), axis.ticks.x=element_blank()) + 
    theme(plot.margin = unit(c(0,0,0,0), "lines")) 

これが可能に両方の方法でパネルマージンに伸びるプロット。