R语言 修改geom_mosaic()图中的颜色

qltillow  于 2023-06-27  发布在  其他
关注(0)|答案(2)|浏览(152)

我想用ggplot2绘制一个马赛克图,并手动选择颜色,即为y轴上的每个类别(A,B,C,D,E,F)选择颜色。目前,我只能使用scale_fill_brewer()命令在x轴(X,Y,Z)上选择每个类别的颜色。

bd <- data.frame(x = c(120,5,15,5,20,100, 400,15,50,80,45,410, 250,15,75,35,40,250), 
y = rep(c("A", "B", "C", "D", "E", "F"), 3),
         z = c(rep("X",6),rep("Y",6),rep("Z",6)))
bd$weight = bd$x/sum(bd$x)

ggplot(bd) +
  geom_mosaic(aes(x = product(y, z), 
                  fill = z, weight = weight), offset = 0.015) +
  scale_fill_brewer(palette=2) +
  #scale_color_brewer(palette=3) +
  theme_mosaic()

输出:

我想在graphs provided in this answer中找到类似的东西。这似乎很简单,但我似乎找不到答案。有人能帮忙吗

ukxgm1gy

ukxgm1gy1#

如果你想通过y轴类别来着色,你必须将这个变量Map到fill上,即做fill = y

library(ggplot2)
library(ggmosaic)

ggplot(bd) +
  geom_mosaic(aes(
    x = product(y, z),
    fill = y, weight = weight
  ), offset = 0.015) +
  scale_fill_brewer(palette = 2) +
  theme_mosaic()

5lhxktic

5lhxktic2#

既然你在你的OP中提到你对手动设置填充颜色感兴趣,这里有一个方法来做。在@stefan answer中,你只需要将scale_fill_brewer(palette=2)行替换为以下内容:

scale_fill_manual(values = c("A" = "firebrick2",
                             "B" = "royalblue",
                             "C" = "gold2",
                             "D" = "orchid2",
                             "E" = "forestgreen",
                             "F" = "orange2"))

您可以在这里查阅ggplot2中的一些预定义颜色名称:ggplot colors

相关问题