gpt4 book ai didi

r - grid.arrange 的背景

转载 作者:行者123 更新时间:2023-12-02 05:08:14 30 4
gpt4 key购买 nike

我已经制作了一个类似于下面代码所描述的图,从而生成了发布的图像。我不知道如何将整个背景设置为与定义子图时使用的相同的“grey80”颜色。 IE。我想用相同的颜色对图之间和图例两侧的白色区域进行着色。这是否有可能实现,也许需要一些奇特的 gridgrob-magic?

这个问题类似于change the background color of grid.arrange output但如果可能的话,我想要一个不使用 png() 函数的解决方案

library(ggplot2)
library(gridExtra)
library(ggthemes)
library(grid)

p1 <- ggplot(iris, aes(x = Sepal.Length, y = Sepal.Width,
colour = Species)) +
ggtitle('Sepal') +
geom_point() + theme_bw() +
theme(rect = element_rect(fill = 'grey80'))


p2 <- ggplot(iris, aes(x = Petal.Length, y = Petal.Width,
colour = Species)) +
ggtitle('Petal') +
geom_point() + theme_bw() +
theme(rect = element_rect(fill = 'grey80'))

grid_arrange_shared_legend <- function(...) {
plots <- list(...)
g <- ggplotGrob(plots[[1]] + theme(legend.position = "bottom"))$grobs
legend <- g[[which(sapply(g, function(x) x$name) == "guide-box")]]
lheight <- sum(legend$height)
grid.arrange(
do.call(arrangeGrob, lapply(plots, function(x)
x + theme(legend.position="none"))),
legend,
ncol = 1,
heights = unit.c(unit(1, "npc") - lheight, lheight))
}

grid_arrange_shared_legend(p1,p2)

Grid arrange plot

最佳答案

升级评论

您可以通过向图形窗口添加灰色背景并然后在上面添加绘图。当您的图例函数使用grid.arrange时,这会生成一个新页面;因此,请添加 newpage=FALSE 或更改为 arrangeGrob 到您的函数中。

你的例子

library(ggplot2)
library(gridExtra)
library(ggthemes)
library(grid)

p1 <- ggplot(iris, aes(x = Sepal.Length, y = Sepal.Width, colour = Species)) +
ggtitle('Sepal') +
geom_point() + theme_bw() +
# by adding colour=grey removes the white border of the plot and
# so removes the lines between the plots
# add panel.background = element_rect(fill = "grey80")
# if you want the plot panel grey aswell
theme(plot.background=element_rect(fill="grey80", colour="grey80"),
rect = element_rect(fill = 'grey80'))

p2 <- ggplot(iris, aes(x = Petal.Length, y = Petal.Width, colour = Species)) +
ggtitle('Petal') +
geom_point() + theme_bw() +
theme(plot.background=element_rect(fill="grey80", colour="grey80"),
rect = element_rect(fill = 'grey80'))

调整你的函数

# Change grid.arrange to arrangeGrob
grid_arrange_shared_legend <- function(...) {
plots <- list(...)
g <- ggplotGrob(plots[[1]] + theme(legend.position = "bottom"))$grobs
legend <- g[[which(sapply(g, function(x) x$name) == "guide-box")]]
lheight <- sum(legend$height)
arrangeGrob( # change here
do.call(arrangeGrob, lapply(plots, function(x)
x + theme(legend.position="none"))),
legend,
ncol = 1,
heights = unit.c(unit(1, "npc") - lheight, lheight))
}

情节

grid.draw(grobTree(rectGrob(gp=gpar(fill="grey80", lwd=0)), 
grid_arrange_shared_legend(p1,p2)))

这给出

enter image description here

关于r - grid.arrange 的背景,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34755362/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com