2012-03-28 11 views
20

È possibile inserire un'immagine raster o un'immagine pdf sotto un geom_line() su un grafico ggplot2?Inserimento di un'immagine in ggplot2

Volevo essere in grado di tracciare rapidamente i dati su un grafico precedentemente calcolato che impiega molto tempo a generare poiché utilizza una grande quantità di dati.

Ho letto attraverso questo example. Tuttavia, poiché ha più di un anno, ho pensato che potrebbe esserci un modo diverso di farlo ora.

risposta

49

prova ?annotation_custom in ggplot2

esempio,

library(png) 
library(grid) 
img <- readPNG(system.file("img", "Rlogo.png", package="png")) 
g <- rasterGrob(img, interpolate=TRUE) 

qplot(1:10, 1:10, geom="blank") + 
    annotation_custom(g, xmin=-Inf, xmax=Inf, ymin=-Inf, ymax=Inf) + 
    geom_point() 
+0

È possibile leggere in un file esterno come '.jpg' o' .pdf' da utilizzare con 'annotation_custom() '? Ho letto alcuni esempi ma l'annotazione sembra essere generata in R. – djq

+4

ho aggiunto un esempio per una bitmap. Con un'immagine vettoriale, dovrai creare un grob con il pacchetto 'grImport'. – baptiste

+0

meraviglioso! Grazie. – djq

8

Solo l'aggiunta di un aggiornamento dal pacchetto Magick eccezionale:

library(ggplot2) 
library(magick) 
library(here) # For making the script run without a wd 
library(magrittr) # For piping the logo 

# Make a simple plot and save it 
ggplot(mpg, aes(displ, hwy, colour = class)) + 
    geom_point() + 
    ggtitle("Cars") + 
    ggsave(filename = paste0(here("/"), last_plot()$labels$title, ".png"), 
     width = 5, height = 4, dpi = 300) 

Cars

# Call back the plot 
plot <- image_read(paste0(here("/"), "Cars.png")) 
# And bring in a logo 
logo_raw <- image_read("http://hexb.in/hexagons/ggplot2.png") 

# Scale down the logo and give it a border and annotation 
# This is the cool part because you can do a lot to the image/logo before adding it 
logo <- logo_raw %>% 
    image_scale("100") %>% 
    image_background("grey", flatten = TRUE) %>% 
    image_border("grey", "600x10") %>% 
    image_annotate("Powered By R", color = "white", size = 30, 
       location = "+10+50", gravity = "northeast") 

# Stack them on top of each other 
final_plot <- image_append(image_scale(c(plot, logo), "500"), stack = TRUE) 
# And overwrite the plot without a logo 
image_write(final_plot, paste0(here("/"), last_plot()$labels$title, ".png")) 

Cars with logo