R语言 指定特定颜色时图例消失[重复]

41zrol4v  于 2023-03-20  发布在  其他
关注(0)|答案(1)|浏览(148)

此问题在此处已有答案

How do I add legend label to a new color point in ggplot? [duplicate](1个答案)
3天前关闭。
我正在创建一个散点图,并使用一个单独的geom_point图层指定颜色。如果我不指定颜色,GGPLOT会给予我一个图例。

mtcars_new <- mtcars %>% mutate(cyl_label = if_else(cyl > 6, "High CYL", ""),
                  carb_label = if_else(carb > 6, "High CARB", ""))

p <-  mtcars_new %>%
  ggplot(aes(x = hp, y = mpg)) + 
  geom_point(size = 3, color = "green4") 

p + geom_point(mtcars_new %>% filter(cyl_label == "High CYL"), 
             mapping = aes(color = cyl_label), size = 3)

但是,如果我提供特定的颜色,GGPLOT不会给予图例。

p + geom_point(mtcars_new %>% filter(cyl_label == "High CYL"), 
             mapping = aes(color = cyl_label), size = 3, color = "grey50")

为什么会发生这种情况?我可以做些什么来解决它?

ogq8wdun

ogq8wdun1#

通过将颜色作为一个参数来设置,你会覆盖color美学,也就是说,它会被“丢弃”,你不会得到一个图例。相反,我建议简单地Map到color美学,并使用scale_color_manual来设置你想要的颜色。

library(dplyr)
library(ggplot2)

mtcars_new <- mtcars %>% mutate(
  cyl_label = if_else(cyl > 6, "High CYL", ""),
  carb_label = if_else(carb > 6, "High CARB", "")
)

mtcars_new %>%
  ggplot(aes(x = hp, y = mpg)) +
  geom_point(aes(color = cyl_label), size = 3) +
  scale_color_manual(
    values = c("High CYL" = "red", "green4"),
    breaks = "High CYL"
  )

相关问题