2012-03-28 29 views
20

¿Es posible insertar una imagen ráster o una imagen en PDF debajo de geom_line() en un diagrama ggplot2?Insertar una imagen en ggplot2

Quería poder rápidamente trazar los datos sobre un gráfico previamente calculado que lleva mucho tiempo generar ya que utiliza una gran cantidad de datos.

Leí a través de este example. Sin embargo, como tiene más de un año, pensé que podría haber una forma diferente de hacer esto ahora.

Respuesta

49

tratar ?annotation_custom en ggplot2

ejemplo,

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

¿Es posible leer en un archivo externo como '.jpg' o' .pdf' para usar con 'annotation_custom() '? Leí algunos ejemplos, pero la anotación parece generarse en R. – djq

+4

Agregué un ejemplo para un mapa de bits. Con una imagen vectorial, tendrá que crear un grob con el paquete 'grImport'. – baptiste

+0

¡maravilloso! Gracias. – djq

8

Simplemente añadiendo una actualización del paquete Magia excelente:

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

Cuestiones relacionadas