首页 > 解决方案 > 为特定类着色

问题描述

library(ggplot2)
ggplot(mpg, aes(displ, hwy, colour = class)) + 
  geom_point()

如果我想为特定的班级着色,让我们说 2 座,代码中的修改是什么

标签: rggplot2

解决方案


尝试这个。您可以将逻辑条件直接包装在colour元素内:

library(ggplot2)
ggplot(mpg, aes(displ, hwy, colour = (class=='2seater'))) + 
  geom_point()+
  labs(color='class')+
  scale_color_discrete(labels=c('TRUE'='2seater','FALSE'='other'))

输出:

在此处输入图像描述

由于图例不会有时尚标题,您可以使用labs()来更改它或遵循@r2evans的非常聪明的建议,创建一个新列来存储逻辑条件的结果,使用dplyr

library(dplyr)
#Code
mpg %>%
  mutate(Color=ifelse(class=='2seater','2seater','Other')) %>%
  ggplot(aes(displ, hwy, colour = Color)) + 
  geom_point()

输出:

在此处输入图像描述

更新:

#Code2
mpg %>% mutate(Color=ifelse(class=='2seater','2seater','Other')) %>%
  ggplot(aes(displ, hwy, colour = Color)) +
  geom_point()+
  scale_color_manual(values = c("2seater" = "#992399", "Other" = "#000000"))+
  geom_smooth(method = 'lm',aes(group=1),show.legend = F)

输出:

在此处输入图像描述


推荐阅读