2012-03-28 10 views
20

Czy jest możliwe wstawienie obrazu rastrowego lub obrazu pdf pod numerem geom_line() na wykresie ?Wstawianie obrazu do ggplot2

Chciałem szybko wyliczyć dane na wcześniej obliczonym wykresie, który zajmuje dużo czasu, ponieważ wymaga dużej ilości danych.

Przeczytałem ten numer example. Ponieważ jednak ma ponad rok, pomyślałem, że może być teraz inny sposób robienia tego.

Odpowiedz

49

spróbować ?annotation_custom w ggplot2

przykład

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

Czy można odczytać w pliku zewnętrznym, takim jak '.jpg' lub' .pdf', który można użyć z 'adnotacja_custom() '? Przeczytałem kilka przykładów, ale wydaje się, że adnotacja została wygenerowana w R. – djq

+4

i dodałem przykład bitmapy. Z obrazem wektorowym, musisz utworzyć grob z pakietem 'grImport'. – baptiste

+0

cudownie! Dziękuję Ci. – djq

8

Wystarczy dodanie aktualizację z niesamowitym opakowaniu Magick:

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