根据facet_wrap(ggplot2)中未使用的分组变量更改条形文本背景颜色?

问题描述 投票:0回答:1

我想知道是否有任何方法可以通过分组变量(group2更改条形文本的背景颜色,该变量不在ggplot中的分面变量(group1)中。例如,在下面显示的图中,我想将上部背景(G1,G2)的颜色更改为红色,将下部背景(G3,G4)更改为蓝色,与点颜色相同。

# Data simulation
library(dplyr);library(ggplot2)
set.seed(1)
x <- runif(500)
y <- 4 * x^2 + rnorm(length(x), sd = 5)
group1 <- ifelse(x < 0.4, "G1", ifelse(x < 0.6, "G2", ifelse(x < 0.8, "G3", "G4")))

x <- x + runif(length(x), -0.5, 0.5)

  df <- data.frame(x = x, y = y, group1 = group1) |> 
  dplyr::mutate(group2=ifelse(group1 %in% c("G1","G2"), "A", "B"))

  ggplot(df, aes(x = x, y = y)) +
  theme_bw()+
  geom_point(aes(x = x, y = y, colour = factor(group2)), show.legend = FALSE, size=3) +
  scale_colour_manual(values = c("red","blue"))+
  facet_wrap(. ~ group1) +
  theme(strip.text = element_text(face = "bold",size = 12,margin = margin(b = 1.2)))

enter image description here

r ggplot2 background-color facet strip
1个回答
0
投票

为条带背景设置不同填充颜色的一种选择是使用

ggh4x
包。在下面的代码中,我只是对颜色进行了硬编码。但对于更复杂的东西,也可以使用颜色映射。

library(ggplot2)
library(ggh4x)

ggplot(df, aes(x = x, y = y)) +
  theme_bw() +
  geom_point(aes(x = x, y = y, colour = factor(group2)),
    show.legend = FALSE, size = 3
  ) +
  scale_colour_manual(values = c("red", "blue")) +
  ggh4x::facet_wrap2(. ~ group1,
    strip = ggh4x::strip_themed(
      background_x = ggh4x::elem_list_rect(
        fill = c(rep("red", 2), rep("blue", 2))
      ),
      text_x = element_text(color = "white")
    )
  ) +
  theme(strip.text = element_text(
    face = "bold",
    size = 12, margin = margin(b = 1.2)
  ))

© www.soinside.com 2019 - 2024. All rights reserved.