是否可以在geom_line()
情节的ggplot2
下方插入光栅图像或pdf图像?
我希望能够快速地在先前计算的绘图上绘制数据,这需要花费很长时间才能生成,因为它使用了大量数据。
我通读了这个example。但是,由于它超过一年,我认为现在可能有不同的方式。
答案 0 :(得分:61)
在?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()
答案 1 :(得分:17)
只需添加极好的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"))
答案 2 :(得分:7)
还可以使用cowplot
R包(cowplot
是ggplot2
的强大扩展)。它还需要magick
软件包。选中此introduction to cowplot vignette。
以下是PNG和PDF背景图片的示例。
library(cowplot)
library(magick)
my_plot <-
ggplot(data = iris,
mapping = aes(x = Sepal.Length,
fill = Species)) +
geom_density(alpha = 0.7)
# Example with PNG (for fun, the OP's avatar - I love the raccoon)
ggdraw() +
draw_image("https://i.stack.imgur.com/WDOo4.jpg?s=328&g=1") +
draw_plot(my_plot)
# Example with PDF
ggdraw() +
draw_image(file.path(R.home(), "doc", "html", "Rlogo.pdf")) +
draw_plot(my_plot)
答案 3 :(得分:2)
按照@baptiste 的回答,如果您使用更具体的注释函数 annotation_raster()
,则不需要加载 grob 包并转换图像。
该更快的选项可能如下所示:
# read picture
library(png)
img <- readPNG(system.file("img", "Rlogo.png", package = "png"))
# plot with picture as layer
library(ggplot2)
ggplot(mapping = aes(1:10, 1:10)) +
annotation_raster(img, xmin = -Inf, xmax = Inf, ymin = -Inf, ymax = Inf) +
geom_point()
由 reprex package (v1.0.0) 于 2021 年 2 月 16 日创建