数据中存在因子 level/color,但使用 scale_color_manual 在图中缺失

Factor level/color present in data but missing from plot using scale_color_manual

这是一些虚拟数据:

dummy <- c(rep("castor", 20), rep("dandelion", 20), rep("goose", 20), rep("teapot", 20), rep("bee", 20), rep("fan" , 20))
groups <- c(rep(c(rep(1, 10), rep(2, 10)), 6))
mydata <- data.frame(a = rnorm(120, 0, 1), b = rnorm(120, 0, 1), dummy = dummy, groups = groups)

这是我编写的函数,用于绘制我从蓝色虚拟列中选择的级别。我希望剩余的级别以灰色绘制。那些剩余的因子水平(让我们称之为参考)现在是硬编码的,这不是问题,因为在我的真实数据中,我有更多的选择水平(让我们称之为测试)来绘制,这就是我为此编写函数的原因。

custom_plot <- function(level){
   df <- subset(mydata, mydata$dummy == level | mydata$groups == "1")

   # Check that the test level is indeed in the subset df
   return(table(df$dummy, df$groups))              

   p <- ggplot(df, aes(x = a, y = b, color = dummy, shape = dummy)) + geom_point() + theme_bw()
   p <- p + scale_color_manual(values = c(level = "blue", "castor" = "gray", "dandelion" = "gray", "fan" = "gray", "goose" = "gray", "teapot" = "gray"))
   p
}

custom_plot("bee")

我不能 post 图像,因为我至少需要 10 个声誉,但基本上我得到的图表具有图例中的测试级别,但图表中缺少实际数据点,并且shape/color 该级别为空白。我尝试使用 breaks、limits 和 labels 参数,但没有任何效果。

感谢您的帮助!

我相信这应该能满足您的需求。如果您只将颜色列表传递给 ggplot,通常会容易得多。我冒昧地向您展示了一种索引颜色的方法,以便您选择的 dummy 级别将是蓝色的级别。

library(ggplot2)
custom_plot <- function(level){
  df <- subset(mydata, mydata$dummy == level | mydata$groups == "1")

  # create colors vector
  idx <- which(levels(mydata$dummy) == level)
  nlev <- nlevels(mydata$dummy)
  colors <- c(rep("gray", idx-1), "blue", rep("gray", nlev-idx))

  p <- ggplot(df, aes(x = a, y = b, color = dummy, shape = dummy)) + 
    geom_point() + 
    theme_bw()
  p <- p + scale_color_manual(values = colors)
  p
}

custom_plot("bee")