【问题标题】:Enforce same color palette for `color` and `fill` of a subset of data对数据子集的“颜色”和“填充”实施相同的调色板
【发布时间】:2019-01-16 09:59:53
【问题描述】:

拥有以下示例数据集:

set.seed(20)
N <- 20
df1 <- data.frame(x = rnorm(N), 
                  y = rnorm(N), 
                  grp = paste0('grp_', sample(1:500, N, T)), 
                  lab = sample(letters, N, T))

#        x      y     grp   lab
# 1   1.163  0.237 grp_104   w
# 2  -0.586 -0.144 grp_448   y
# 3   1.785  0.722  grp_31   m
# 4  -1.333  0.370 grp_471   z
# 5  -0.447 -0.242 grp_356   o

我想绘制所有点,但只标记它们的子集(例如,那些df1$x&gt;0)。当我对geom_pointgeom_text 使用相同的color=grp 美学时,它工作正常:

ggplot(df1, aes(x=x,y=y,color=grp))+
  geom_point(size=4) +
  geom_text(aes(label=lab),data=df1[df1$x>1,],size=5,hjust=1,vjust=1)+
  theme(legend.position="none")

但如果我想将点设计更改为fill=grp,标签的颜色将不再匹配:

ggplot(df1, aes(x=x,y=y))+
  geom_point(aes(fill=grp),size=4,shape=21) + 
  geom_text(aes(label=lab,color=grp),data=df1[df1$x>1,],size=5,hjust=1,vjust=1)+
  theme(legend.position="none")

我知道调色板是不同的,因为子集的级别与整个数据集的级别不同。但是,使用相同调色板强制执行的最简单解决方案是什么?

【问题讨论】:

    标签: r ggplot2


    【解决方案1】:

    问题是由文本和填充颜色的不同因素水平引起的。我们可以通过在scale_*_discrete 中使用drop = FALSE 来避免丢弃未使用的因子水平:

    ggplot(df1, aes(x=x,y=y))+
      geom_point(aes(fill=grp),size=4,shape=21) +
      geom_text(aes(label=lab,color=grp),data=df1[df1$x>1,],size=5,hjust=1,vjust=1)+
      theme(legend.position="none") +
      scale_fill_discrete(drop = F) +
      scale_colour_discrete(drop = F)
    


    更新

    使用您的真实数据,我们需要确保 grp 实际上是 factor

    # Load sample data
    load("df1.Rdat")
    
    # Make sure `grp` is a factor
    library(tidyverse)
    df1 <- df1 %>% mutate(grp = factor(grp))
    # Or in base R
    # df1$grp = factor(df1$grp)
    
    # Same as before
    ggplot(df1, aes(x=x,y=y))+
      geom_point(aes(fill=grp),size=4,shape=21) +
      geom_text(aes(label=lab,color=grp),data=df1[df1$x>1,],size=5,hjust=1,vjust=1)+
      theme(legend.position="none") +
      scale_fill_discrete(drop = F) +
      scale_colour_discrete(drop = F)
    

    【讨论】:

    • 非常感谢!我真的很喜欢您的解决方案,但是...由于某些奇怪的原因,当我将 exactly 相同的代码应用于我的真实数据集时,它不起作用。如果您能看一下,我将不胜感激,我已将其保存在此处-dropbox.com/s/htndrzurpbogyxk/df1.Rdat?dl=1-只需下载然后load('df1.Rdat'),您会看到标签颜色不匹配...
    • @VasilyA 您需要确保grpfactor(不是character 向量)。我已经更新了我的答案来演示。
    【解决方案2】:

    一种方法是单独保留颜色/填充调色板,并将所有不需要的标签设置为透明:

    ggplot(df1, aes(x = x, y = y)) +
      geom_point(aes(fill = grp), size = 4, shape = 21) +
      geom_text(aes(label = lab, color = grp,
                    alpha = x > 1),
                size = 5, hjust = 1, vjust = 1) +
      scale_alpha_manual(values = c("TRUE" = 1, "FALSE" = 0)) +
      theme(legend.position = "none")
    

    【讨论】:

    • 谢谢@Z.Lin,这是一个聪明的解决方法!在我有 800 个数据点和相同数量的grp...
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-07-27
    • 2020-10-03
    • 1970-01-01
    • 2014-10-27
    • 1970-01-01
    • 2012-07-10
    • 2016-05-19
    相关资源
    最近更新 更多