我想在地图上绘制一些箭头。通过一些谷歌搜索,我了解到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()
然而,当我运行这个脚本时,我只有箭头而不是背景图像:
est_err_structured.csv
floorplan.png
答案 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()
您需要将地图width
和height
传递给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()