R ggplot背景图片没有显示

时间:2016-08-10 06:45:29

标签: r ggplot2

问题

我想在地图上绘制一些箭头。通过一些谷歌搜索,我了解到annotation_custom rasterGrob可以做到这一点:

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

img = readPNG('floorplan.png')
g = rasterGrob(img, interpolate = TRUE)

data = read.csv('est_err_structured.csv', header = FALSE)
x1 = data$V1
y1 = data$V2
x2 = data$V3
y2 = data$V4

p = ggplot() +
geom_segment(data = data, mapping = aes(x = x1, y = y1, xend = x2, yend = y2),
            arrow = arrow(length = unit(0.2, 'cm'))) +
annotation_custom(g, xmin = -Inf, xmax = Inf, ymin = -Inf, ymax = Inf) +
xlab('x (m)') +
ylab('y (m)') +
theme_bw()

pdf('err_on_map.pdf')
p
dev.off()

然而,当我运行这个脚本时,我只有箭头而不是背景图像:

enter image description here

附件

参考

1 个答案:

答案 0 :(得分:3)

你需要多学习一下ggplot2。例如,aes中映射的变量取自定义为data的data.frame,在此示例中,您必须将其传递给ggplot。我认为annotation_custom不知何故需要它来获得正确的坐标或尺寸。

p = ggplot(data) +
  annotation_custom(g, xmin = -Inf, xmax = Inf, ymin = -Inf, ymax = Inf) +
  geom_segment(aes(x = V1, y = V2, xend = V3, yend = V4),
               arrow = arrow(length = unit(0.2, 'cm'))) +
  xlab('x (m)') +
  ylab('y (m)') +
  theme_bw()

您需要将地图widthheight传递给pdf,才能使图像与地图正确对齐。

resulting plot

修改

@baptiste推荐annotation_raster,这使定位更容易:

ggplot(data) +
  annotation_raster(img, xmin = 50, xmax = 600, ymin = 20, ymax = 400) +
  geom_segment(aes(x = V1, y = V2, xend = V3, yend = V4),
               arrow = arrow(length = unit(0.2, 'cm'))) +
  coord_cartesian(xlim = c(50, 600), ylim = c(20, 400)) +
  xlab('x (m)') +
  ylab('y (m)') +
  theme_bw()

resulting plot 2