【问题标题】:Change default colors in ggpairs using variable assignments使用变量分配更改 ggpairs 中的默认颜色
【发布时间】:2023-02-26 10:27:44
【问题描述】:

我有代码来创建一个散点图矩阵,其中包含我希望根据数据集中的分类变量对其进行着色的密度曲线。我需要它来匹配特定的颜色,但我似乎无法让颜色从默认值更新。

下面是我试图用一个众所周知的数据集完成的概念示例(因为我的数据包含敏感信息并且无法发布)。

例如,如果我想使用 R 中的 crabs 数据集创建它,我会将分类变量分配给颜色和符号,例如:

species <- ifelse(crabs$sp == "B", "blue", "orange")
gender <- ifelse(crabs$sex == "M", "O", "+")

然后我想在我的矩阵和密度图中使用完全相同的符号和颜色:

ggpairs(crabs, columns=4:8, aes(color=species, shape=gender),
        lower=list(continuous="smooth"), diag=list(continuous="densityDiag"))

但是,这会输出以下内容:


But the coral color should be blue, and the teal color should be true orange.

【问题讨论】:

    标签: r ggplot2 ggpairs


    【解决方案1】:

    更改 ggpairs 的默认颜色并不容易,这里的问题特别在于右上角的相关文本,这意味着 scale_colour_identity() 将不起作用。您可以改为使用手动比例来定义颜色:

    species <- ifelse(crabs$sp == "B", "blue", "orange")
    gender <- ifelse(crabs$sex == "M", "O", "+")
    
    ggpairs(crabs, columns=4:8, aes(color=species,
                                    shape=gender),
            lower=list(continuous="smooth"),
            diag=list(continuous="densityDiag")) +
      scale_fill_manual(values = c("blue", "orange")) +
      scale_colour_manual(values = c("blue", "orange"))
    

    在这里,我建议您将 species 中的值称为更有意义的值,以便在相关图中获得更好的标签。我通常还建议为 aes() 中的颜色传递一列数据而不是外部向量。你可以用 scale_shape_manual() 对这些点做类似的事情。

    【讨论】:

      【解决方案2】:

      您可能需要使用 scale_color_manual() 和 scale_fill_manual() 为每个组指定颜色。此外,颜色值必须与类别数相同,而不是数据的长度:

      ggpairs(crabs, columns=4:8, aes(colour=species, shape=gender),
              lower=list(continuous="smooth"), diag=list(continuous="densityDiag"))+
        scale_color_manual(values = unique(species))+
        scale_fill_manual(values = unique(species))
      

      【讨论】:

        猜你喜欢
        • 2017-02-02
        • 2018-09-13
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-05-15
        • 2016-03-21
        • 2021-01-16
        • 1970-01-01
        相关资源
        最近更新 更多