在小平面STRIP背景中的多种颜色

 手机用户2602898385 发布于 2023-01-09 17:34

我想根据组修改构面背景的颜色.我不确定这是否可行.具体来说,我使用facet_grid(不facet_wrap)多层.

## Sample data
dat <- mtcars
## Add in some colors based on the data
dat$facet_fill_color <- c("red", "green", "blue", "yellow", "orange")[dat$gear]

## Create main plot
library(ggplot2)
P <- ggplot(dat, aes(x=cyl, y=wt)) + geom_point(aes(fill=hp)) + facet_grid(gear+carb ~ .)

## I can easily cahnge the background using: 
P + theme(strip.background = element_rect(fill="red"))

但是,我想为不同的组改变颜色.理想情况下,如下所示(当然不起作用)

P + theme(strip.background = element_rect(fill=dat$facet_fill_color))
P + theme(strip.background = element_rect(aes(fill=facet_fill_color)))

小平面背景可以有多种颜色吗?

(相关,但不是上面的实际答案: ggplot2:基于数据集中变量的facet_wrap条带颜色)

1 个回答
  • 对于它的价值而言,适应之前的gtable hack非常简单.

    在此输入图像描述

    ## Sample data
    require(ggplot2)
    dat <- mtcars
    ## Add in some colors based on the data
    dat$facet_fill_color <- c("red", "green", "blue", "yellow", "orange")[dat$gear]
    
    ## Create main plot
    p <- ggplot(dat, aes(x=cyl, y=wt)) + 
      geom_point(aes(fill=hp)) + facet_grid(gear+carb ~ .) +
      theme(strip.background=element_blank())
    
    dummy <- p
    dummy$layers <- NULL
    dummy <- dummy + geom_rect(data=dat, xmin=-Inf, ymin=-Inf, xmax=Inf, ymax=Inf,
                               aes(fill = facet_fill_color))
    
    library(gtable)
    
    g1 <- ggplotGrob(p)
    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-right", g2$layout$name)
    g2$grobs[strips] <- replicate(sum(strips), nullGrob(), simplify = FALSE)
    g2$layout$l[panels] <- g2$layout$l[panels] + 1
    g2$layout$r[panels] <- g2$layout$r[panels] + 2
    
    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 <- 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)
    

    2023-01-09 17:36 回答
撰写答案
今天,你开发时遇到什么问题呢?
立即提问
热门标签
PHP1.CN | 中国最专业的PHP中文社区 | PNG素材下载 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有