绘图坐标不要与* jpg图像坐标配合使用

时间:2020-04-16 19:33:58

标签: r image ggplot2 jpeg raster

我想使用通过ggplot2包创建的原始绘图坐标为jpg图像中的一个椭圆对象创建一个框坐标。在我的示例中:

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

但是,如果我看下面的图,我会发现jpg图像和框坐标中的椭圆不匹配:

ellipsetest

如果我尝试将x和y坐标乘以或除以图像的宽度和高度,则不会绘制框坐标。

请问有什么提示吗?

谢谢

1 个答案:

答案 0 :(得分:1)

您必须在ggplot中将原点强制为(0,0)。 试试这个:

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)

此外,您需要相应地更改dpi

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