【问题标题】:How can I change the color of my facet label (strip.background) to be the same as its bars?如何将构面标签 (strip.background) 的颜色更改为与其条形相同?
【发布时间】:2020-11-26 10:04:52
【问题描述】:

我有一个facet_grid 图,它总结了每个类别的基因分布,如下所示。我想更改构面标签/strip.background(代码中带有红色框和“类别”的那个)的颜色,使其与其对应的图相似。

如何增加条之间的间距(而不是刻面之间的间距)以使其更具可读性?由于您可以在 y 轴标签(被黑框覆盖)上看到大量数据,因此它们正在被压缩并且标签变得不可读。

ggplot(allVFs, aes(x=Dist,y=genes)) + 
  geom_bar(stat="identity", width = 0.75, size = 0.05 ) +
  facet_grid(Categories ~., scales = "free", space = "free") +
  labs( x = "Distribution (%)", y = "Genes", title = "VFs per category" ) +
  theme( strip.text = element_text( size = 8, color = "white", hjust = 0.5),
         strip.text.y = element_text(angle=0),
         strip.background = element_rect( fill = "#5675D6"), # I tried changing this but couldn't make it similar to the bar colors
         panel.background = element_rect( fill = "#efefef"),
         panel.grid.major.x = element_blank(),
         panel.grid.minor.x = element_blank(),
         panel.grid.minor.y = element_blank(),
         panel.grid.major.y = element_line( color = "#C0C0C0" ),
         panel.spacing.x = unit( 0.8, "cm" ),
         panel.spacing.y = unit( 0.5, "cm" ),
         legend.position = "none" ) +
  geom_text(aes( label = paste0( Dist, "%" ), y = genes),
            vjust = 0, size = 2, color = "black" ) +
  aes(fill = as.factor(Categories)) #This gives the color to each facet that I want to replicate with the facet labels

任何改进此情节的建议将不胜感激!

【问题讨论】:

    标签: r ggplot2 geom-bar facet-grid


    【解决方案1】:

    这在ggplot2 中是不可能开箱即用的,但我们可以深入研究gtable 对象来实现结果。

    我将使用示例图和数据。但这也适用于您的示例:

    library(ggplot2)
    g <- ggplot(iris, aes(x = Sepal.Length, fill = Species)) +
      geom_bar() +
      facet_grid(Species ~ .)
    
    # Find the colors used
    fill_colors <- unique(ggplot_build(g)$data[[1]]$fill)
    
    # Find strips glob
    gt<-ggplot_gtable(ggplot_build(g))
    strips <- which(startsWith(gt$layout$name,'strip'))
    
    # Change the fill color of each strip
    for (s in seq_along(strips)) {
      gt$grobs[[strips[s]]]$grobs[[1]]$children[[1]]$gp$fill <- fill_colors[s]
    }
    
    plot(gt)
    

    reprex package (v0.3.0) 于 2020 年 11 月 26 日创建

    我们正在做的是找到包含每个条带的网格对象,并使用从图中提取的颜色手动更改其填充属性。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2023-01-26
      • 1970-01-01
      • 2023-04-06
      • 1970-01-01
      • 1970-01-01
      • 2020-03-22
      • 2016-04-28
      相关资源
      最近更新 更多