dww answer to my following stackoverflow post:
how to fit the plot over a background image in R and ggplot2
has me quite close to almost where I want to be. Except that when I combine the plot drawn in the previous plot, the plot with the background image 'bleeds' into the plot panel area whereas the other plot doesn't. this is shown in the screenshot below:
See the panel space at the top of the first plot and how the plot with the background image on the right has its image expand to fill up the plot panel area. If I remove the background image, then both the plots are aligned perfectly. I am trying to limit the background image to NOT extend and fill up the panel area both at the top and bottom. I do not know how to do that. The sample code is shown below:
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)