【问题标题】:R ggplot background image not showingR ggplot背景图像未显示
【发布时间】:2016-08-10 16:00:18
【问题描述】:

问题

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

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

但是,当我运行这个脚本时,我只有箭头,但没有背景图片:

附件

参考文献

【问题讨论】:

  • 只是好奇,这是你的猫的 GPS 追踪器数据吗?

标签: r ggplot2


【解决方案1】:

你需要多研究一下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 以便将图像与绘图正确对齐。

编辑:

@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()

【讨论】:

  • 有人可能会说这是一个错误,因为任何 data.frame,例如ggplot(iris),会的。
  • @baptiste 我依稀记得你说过annotation_custom 是一个可怕的黑客。 :)
  • 一个有缺陷/未完成的功能,是的。但仍然非常有用(我认为一个可怕的黑客是当它与 clip=off 结合将东西放在面板之外时)。无论如何,这里的 annotation_raster 也可以工作。
  • @baptiste 是的,但它似乎有相同的“错误”。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-04-02
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多