gpt4 book ai didi

r - ggplot2:facet_wrap 基于数据集中变量的 strip 颜色

转载 作者:行者123 更新时间:2023-12-03 05:57:11 25 4
gpt4 key购买 nike

有没有办法根据数据框提供的变量来填充使用facet_wrap创建的面条?

示例数据:

MYdata <- data.frame(fruit = rep(c("apple", "orange", "plum", "banana", "pear", "grape")), farm = rep(c(0,1,3,6,9,12), each=6), weight = rnorm(36, 10000, 2500), size=rep(c("small", "large")))

示例图:

p1 = ggplot(data = MYdata, aes(x = farm, y = weight)) + geom_jitter(position = position_jitter(width = 0.3), aes(color = factor(farm)), size = 2.5, alpha = 1) + facet_wrap(~fruit)

我知道如何更改 strip 的背景颜色(例如更改为橙色):

p1 + theme(strip.background = element_rect(fill="orange"))

facet_wrap and orange strip color

有没有办法传递变量 size 中的值在MYdata到参数fillelement_rect

基本上,我希望小水果(苹果、李子、梨)的 strip 背景颜色为绿色,而大水果(橙子、香蕉、葡萄)的背景颜色为红色,而不是所有 strip 都使用一种颜色。

最佳答案

只需做一点工作,您就可以将您的绘图与具有正确 grobs 的虚拟 gtable 结合起来,

enter image description here

d <- data.frame(fruit = rep(c("apple", "orange", "plum", "banana", "pear", "grape")), 
farm = rep(c(0,1,3,6,9,12), each=6),
weight = rnorm(36, 10000, 2500),
size=rep(c("small", "large")))

p1 = ggplot(data = d, aes(x = farm, y = weight)) +
geom_jitter(position = position_jitter(width = 0.3),
aes(color = factor(farm)), size = 2.5, alpha = 1) +
facet_wrap(~fruit)

dummy <- ggplot(data = d, aes(x = farm, y = weight))+ facet_wrap(~fruit) +
geom_rect(aes(fill=size), xmin=-Inf, xmax=Inf, ymin=-Inf, ymax=Inf) +
theme_minimal()

library(gtable)

g1 <- ggplotGrob(p1)
g2 <- ggplotGrob(dummy)

gtable_select <- function (x, ...)
{
matches <- c(...)
x$layout <- x$layout[matches, , drop = FALSE]
x$grobs <- x$grobs[matches]
x
}

panels <- grepl(pattern="panel", g2$layout$name)
strips <- grepl(pattern="strip_t", g2$layout$name)
g2$layout$t[panels] <- g2$layout$t[panels] - 1
g2$layout$b[panels] <- g2$layout$b[panels] - 1

new_strips <- gtable_select(g2, panels | strips)
grid.newpage()
grid.draw(new_strips)

gtable_stack <- function(g1, g2){
g1$grobs <- c(g1$grobs, g2$grobs)
g1$layout <- transform(g1$layout, z= z-max(z), name="g2")
g1$layout <- rbind(g1$layout, g2$layout)
g1
}
## ideally you'd remove the old strips, for now they're just covered
new_plot <- gtable_stack(g1, new_strips)
grid.newpage()
grid.draw(new_plot)

关于r - ggplot2:facet_wrap 基于数据集中变量的 strip 颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19440069/

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