Bru*_*uno 2 background r image ggplot2
如何使用图像作为 ggplot2 图的背景?
例如,代码:
mtcars %>%
ggplot(aes(cyl)) +
geom_bar() +
theme(plot.background = element_rect(fill = "black"))
Run Code Online (Sandbox Code Playgroud)
结果如下:

并且背景颜色为黑色。
如何选择图像作为背景,而不仅仅是选择其颜色?
我们可以使用ggpubr::background_image. 这是一个可重现的最小示例
library(ggpubr)
library(jpeg)
# Download and read sample image (readJPEG doesn't work with urls)
url <- "http://mathworld.wolfram.com/images/gifs/rabbduck.jpg"
download.file(url, destfile = "rabbduck.jpg")
img <- readJPEG("rabbduck.jpg")
ggplot(iris, aes(Species, Sepal.Length)) +
background_image(img) +
geom_boxplot(aes(fill = Species))
Run Code Online (Sandbox Code Playgroud)
要将整个画布用作背景图像的绘图区域,您可以使用ggimage::ggbackground(感谢@Marius)
library(ggimage)
g <- ggplot(iris, aes(Species, Sepal.Length)) +
geom_boxplot(aes(fill = Species))
ggbackground(g, url)
Run Code Online (Sandbox Code Playgroud)
小智 3
你可以将一个绘制在另一个之上,
library(ggplot2)
p <- ggplot(mtcars, aes(cyl)) +
geom_bar() +
theme(plot.background = element_rect(fill=NA))
library(grid)
grid.draw(gList(rasterGrob(img, width = unit(1,"npc"), height = unit(1,"npc")),
ggplotGrob(p)))
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1948 次 |
| 最近记录: |