Search code examples
rimageggplot2jpegraster

Plot coordinates don't mach with *jpg image coordinates


I've like to create a box coordinates for one ellipse object in a jpg image using original plot coordinates created using ggplot2 package. In my example:

#Packages
library(ggplot2)
library(ggforce)
library(raster)

#Create a ellipse using ggplot2
ell.sim<-ggplot() +
  geom_ellipse(aes(x0 = 200, y0 = 200, a = 150, b = 50, angle = 0), fill="black") +
  coord_fixed(xlim=c(0,1000),ylim=c(0,1000)) 
ell.sim2 <- ell.sim + theme_void()
plot(ell.sim2)


#Save in JPG format with 96 DPI 
ggsave(
  filename="ellipse_test.jpg",
  plot = ell.sim2,
  width = 10,
  height = 10,
  dpi = 96) 

#Open jpg created with raster
img <- stack("ellipse_test.jpg")
plotRGB(img) 
#

#Extract the ellipse limits for the box coordinate creation
ell.sim.coords <- ggplot_build(ell.sim2)
x1<-(min(ell.sim.coords$data[[1]]$x))
x2<-(max(ell.sim.coords$data[[1]]$x))
y1<-(min(ell.sim.coords$data[[1]]$y))
y2<-(max(ell.sim.coords$data[[1]]$y))
bbx<-c(x1,x1,x2,x2,x1)
bby<-c(y1,y2,y2,y1,y1)
lines(bbx,bby,col="red")
#

But If I look at the image plot below I see that the ellipse in the jpg image and box coordinates doesn't match:

ellipsetest

And if I try to multiply or divide the x and y coordinates by the width and height of the image the box coordinates are not plotted.

Please, any tips?

Thanks


Solution

  • You have to force the origin to (0,0) in ggplot. Try This:

    ell.sim<-ggplot() +
      geom_ellipse(aes(x0 = 200, y0 = 200, a = 150, b = 50, angle = 0), fill="black") +
      coord_fixed(xlim=c(0,1000),ylim=c(0,1000)) + 
      scale_y_continuous(expand = c(0, 0)) +scale_x_continuous(expand = c(0, 0))
    
    ell.sim2 <- ell.sim + theme_void()
    plot(ell.sim2)
    

    Also, you need to change the dpi accordingly

    ggsave(
      filename="ellipse_test.jpg",
      plot = ell.sim2,
      width = 10,
      height = 10,
      dpi = 100) 
    
    img <- stack("ellipse_test.jpg")
    plotRGB(img) 
    
    ell.sim.coords <- ggplot_build(ell.sim2)
    x1<-(min(ell.sim.coords$data[[1]]$x))
    x2<-(max(ell.sim.coords$data[[1]]$x))
    y1<-(min(ell.sim.coords$data[[1]]$y))
    y2<-(max(ell.sim.coords$data[[1]]$y))
    bbx<-c(x1,x1,x2,x2,x1)
    bby<-c(y1,y2,y2,y1,y1)
    lines(bbx,bby,col="red")
    

    enter image description here