在“ggplot2::ggplot()”箱线图中同时为背景中的框和阴影区域手动分配颜色

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

我正在尝试手动为

ggplot2::ggplot()
箱线图分配颜色。使用
ggplot2::geom_rect()
函数,我知道如何手动为方框分配颜色,并且还知道如何为散点图等其他类型的绘图手动为背景中的阴影区域分配颜色。我不知道如何手动将颜色分配给箱线图背景中的阴影区域(当我尝试这样做时,它似乎自动将颜色分配给盒子而不是我想要着色的背景区域),而且我也不知道同时为背景中的框和阴影区域手动分配颜色。

这是一些虚构的数据。

Data_Frame <- data.frame(Group_1 = rep(rep(letters[1:2], each = 5), 5), Group_2 = as.character(c(rep(1, 20), rep(2, 30))), Group_3 = rep(rep(LETTERS[1:5], each = 10), length.out = 50), Response_Variable = rnorm(50))
Group_1_Colors <- data.frame(Group_1 = letters[1:2], Group_1_Color = c('red4', 'blue4'))
Group_2_Colors <- data.frame(Group_2 = as.character(1:2), Group_2_Color = c('yellow1', 'purple1'))
Group_2_Colors$Minimum_Horizontal_Cutoff_Value <- c(-Inf, 2.5)
Group_2_Colors$Maximum_Horizontal_Cutoff_Value <- c(2.5, Inf)
Final_Data_Frame <- merge(Data_Frame, Group_2_Colors, by = 'Group_2', all = T)
Final_Data_Frame <- merge(Final_Data_Frame, Group_1_Colors, by = 'Group_1', all = T)

首先,我们将加载包。

if (!require (ggplot2)) {
  install.packages('ggplot2')
}
library(ggplot2)

这是一个图,我手动为方框指定了颜色,并通过另一个变量在背景中绘制了阴影区域。

ggplot2::ggplot(Final_Data_Frame, aes(x = Group_3, y = Response_Variable, fill = Group_1)) +
  ggplot2::geom_boxplot() +
  ggplot2::scale_fill_manual(values = Group_1_Colors$Group_1_Color) +
  ggplot2::geom_rect(aes(xmin = Minimum_Horizontal_Cutoff_Value, xmax = Maximum_Horizontal_Cutoff_Value, ymin = -Inf, ymax = Inf), alpha = 0.009)

当我再次尝试使用“ggplot2::geom_rect()”函数手动为背景中的阴影区域着色时,它会覆盖分配给框的先前颜色,并用这些颜色为框着色。

ggplot2::ggplot(Final_Data_Frame, aes(x = Group_3, y = Response_Variable, fill = Group_1)) +
  ggplot2::geom_boxplot() +
  ggplot2::scale_fill_manual(values = Group_1_Colors$Group_1_Color) +
  ggplot2::geom_rect(aes(xmin = Minimum_Horizontal_Cutoff_Value, xmax = Maximum_Horizontal_Cutoff_Value, ymin = -Inf, ymax = Inf), alpha = 0.009) +
  ggplot2::scale_fill_manual(values = Group_2_Colors$Group_2_Color)

有什么解决办法吗? 这个问题似乎会有所帮助,但我仍然无法弄清楚。即使我在前一句中链接的问题有帮助,我也不认为可以将图例分成两组,

Group_2
Group_3
,这是我希望的两个单独的组手动着色;我也想打破这两个团体的传说。

谢谢!

r ggplot2 boxplot
1个回答
0
投票

您可以使用

ggnewscale
包轻松获得矩形的单独图例,该包允许具有相同美学的多个比例和图例。

注意:另请注意,恕我直言,为背景矩形使用单独的数据框会更容易。将所有信息放入一个数据框中会产生副作用,即您会在彼此之上绘制多个矩形,这就是您必须设置非常小的

alpha
值的原因。

library(ggplot2)

ggplot(
  Final_Data_Frame,
  aes(
    x = Group_3, y = Response_Variable,
    fill = Group_1
  )
) +
  geom_boxplot() +
  scale_fill_manual(
    values = Group_1_Colors$Group_1_Color
  ) +
  ggnewscale::new_scale_fill() +
  geom_rect(
    data = Group_2_Colors,
    aes(
      xmin = Minimum_Horizontal_Cutoff_Value,
      xmax = Maximum_Horizontal_Cutoff_Value,
      ymin = -Inf, ymax = Inf,
      fill = factor(Group_2)
    ),
    alpha = 0.2,
    inherit.aes = FALSE
  ) +
  scale_fill_manual(
    values = Group_2_Colors$Group_2_Color,
    name = "Group_2"
  )

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