0

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: enter image description here

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)
Community
  • 1
  • 1
Bharat
  • 2,409
  • 6
  • 32
  • 57

1 Answers1

0

So Here is what I have found which kind of works. I don't know if that is the best way to handle it, but in both the plots, I put expand = c(0,0) within both scale_y_reverse and scale_x_continuous like shown below:

  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"))

This allows the plots to stretch into the panel margins both ways.

Bharat
  • 2,409
  • 6
  • 32
  • 57