Wrong background image of R ggplot

Problem

I want to draw some arrows on the map. With some search engines, I found out what annotation_customs rasterGrobcan do the following:

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

However, when I run this script, I got only arrows, but not a background image:

enter image description here

application

References

+4
source share
1 answer

ggplot2 . , , aes, data.frame, data, 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, .

final schedule

Edit:

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

final chart 2

+3

Source: https://habr.com/ru/post/1650765/


All Articles