【问题标题】:ggplot2 - opposite colors for fill without recodingggplot2 - 填充的相反颜色无需重新编码
【发布时间】:2020-05-05 19:01:56
【问题描述】:

我想生成一个情节并按性别分层。不幸的是,我的 df 编码方式是男性在情节中是红色的,女性是蓝色的。

df <- data.frame(sex = rbinom(1000, 1, .5),
                 age = rnorm(1000, mean = 50, sd = 10))
df$sex <- as.factor(df$sex)

我可以使用 scale_color_manual 切换颜色,但 bin 没有填充,而且轮廓不方便。

ggplot(df, aes(x = age, color = sex))+
geom_histogram(position = "identity")+
scale_color_manual(values = c("#00BFC4", "#F8766D"))

如何正确操作?提前致谢!

【问题讨论】:

    标签: r ggplot2


    【解决方案1】:

    如果我正确理解您的问题,您可以通过将性别映射到 fill 来解决此问题。

    df <- data.frame(sex = rbinom(1000, 1, .5),
                 age = rnorm(1000, mean = 50, sd = 10))
    df$sex <- as.factor(df$sex)
    
    
    ggplot(df, aes(x = age, fill = sex))+
    geom_histogram(position = "identity")+
    scale_fill_manual(values = c("#00BFC4", "#F8766D"))
    

    之后,您可以切换颜色以正确匹配

    【讨论】:

      【解决方案2】:

      我认为您想在aes 调用中指定fill 而不是colour,并使用scale_fill_manual 而不是scale_colour_manual。如果您也使用position = "dodge",您可以更好地比较两组:

      ggplot(df, aes(x = age, fill = sex)) +
        geom_histogram(position = "dodge", colour = "black") +
        scale_fill_manual(values = c("pink", "blue"))
      

      【讨论】:

        猜你喜欢
        • 2018-12-12
        • 2016-09-13
        • 2021-11-29
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-03-02
        • 1970-01-01
        相关资源
        最近更新 更多