Home > OS >  Align points with background png in ggplot2
Align points with background png in ggplot2

Time:02-15

I am trying to crease a grid of points corresponding to luminescence values in a 384-well plate experiment. I am drawing the plate as a .png file and overlaying the grid such that each point should sit in one well of the plate. Example code and data provided.

Is it possible to do this with ggplot2?

I am using the following code (example data provided):

library(ggplot2)
library(png)
library(RCurl)
library(grid)

example.gg <- read.csv("https://docs.google.com/spreadsheets/d/e/2PACX-1vRcX5aMZGCp9Bs3BRZSg8k4o-kbSjOO5z3LsRxgIv4qJHz1fG-Argruje32OuZ2Tt2qPaNGksGr4Jia/pub?output=csv",
            row.names = 1)
example.gg$Row <- factor(example.gg$Row, levels = sort(unique(example.gg$Row)))

png.img <- readPNG(getURLContent("https://i.imgur.com/QeSO7d3.png"))
img.rg <- rasterGrob(png.img, interpolate=TRUE)

gp <- ggplot(example.gg,
             aes(x = Col, y = Row, col = Lum))  
  annotation_custom(img.rg, xmin=-Inf, xmax=Inf, ymin=-Inf, ymax=Inf)  
  geom_point(shape = 15)   
  theme_void()
gp

And this is the image that gets made:

enter image description here

Answer

Thanks to enter image description here

CodePudding user response:

By manually adjusting the position of the image with xmin/xmax & ymin/ymax, fixing the pitch of rows and columns with coord_fixed(clip = "off) and expanding the plot.margin in theme I was able to get something that seems like it will work.

library(ggplot2)
library(png)
library(RCurl)
library(grid)

example.gg <- read.csv("https://docs.google.com/spreadsheets/d/e/2PACX-1vRcX5aMZGCp9Bs3BRZSg8k4o-kbSjOO5z3LsRxgIv4qJHz1fG-Argruje32OuZ2Tt2qPaNGksGr4Jia/pub?output=csv",
            row.names = 1)
example.gg$Row <- factor(example.gg$Row, levels = sort(unique(example.gg$Row)))

png.img <- readPNG(getURLContent("https://i.imgur.com/QeSO7d3.png"))
img.rg <- rasterGrob(png.img, interpolate=TRUE)

gp <- ggplot(example.gg,
       aes(x = Col, y = Row, col = Lum))  
  annotation_custom(
    img.rg,
    xmin = -2,
    xmax = 27,
    ymin = -1,
    ymax = 18
  )  
  geom_point(shape = 15)  
  coord_fixed(clip = "off")  
  theme_void()  
  theme(plot.margin = unit(c(3, 2, 5, 2), "lines"))
  
gp

Created on 2022-02-14 by the reprex package (v2.0.1)

  • Related