将图像插入到ggplot2
问题描述:
是否可以在图上的geom_line()
下插入光栅图像或pdf图像?将图像插入到ggplot2
我想快速地将数据绘制在之前计算的绘图上,这需要很长时间才能生成,因为它使用大量数据。
我通过这个example阅读。然而,因为它已经超过一岁了,我认为现在可能有不同的方式。
答
尝试?annotation_custom
在ggplot2
例如,
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()
答
只是增加从了不起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)
# 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"))
是否可以在'annotation_custom()'中使用外部文件(例如'.jpg'或'.pdf')来读取?我通读了一些例子,但注释似乎是在R.中生成的。 – djq 2012-03-29 00:48:28
我添加了一个位图的例子。使用矢量图像,您需要使用'grImport'软件包创建一个grob。 – baptiste 2012-03-29 01:17:57
太棒了!谢谢。 – djq 2012-03-29 01:19:55