r - 为特定类着色
问题描述
library(ggplot2)
ggplot(mpg, aes(displ, hwy, colour = class)) +
geom_point()
如果我想为特定的班级着色,让我们说 2 座,代码中的修改是什么
解决方案
尝试这个。您可以将逻辑条件直接包装在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)
输出:
推荐阅读
- scala - 如何注入随机数。加特林的用户?
- android - 将提交按钮添加到 SearchView
- material-ui - 将 @material-ui/core 与 NextJS/React 一起使用时的 FOUC
- ios - 呼叫目录分机 - 未找到分机
- postgresql - 无法创建数据库 - psql:致命:角色“dyadav”不存在 - Mac OS
- excel - 如何跳过计算出现在另外 2 列集中的 2 列中的相同值集
- python - 点安装
塞住了。弹出从 pip==9.0.1 升级到 pip==19.0.3 的消息。如何使用 pip 9.0.1 安装任何新软件包? - reactjs - 如何修复“HTML5 currentTime 始终设置为零”
- html - Python 3.5 中的 PDF 到 HTML
- arraylist - 我们如何在 HashMap 中的 ArrayList 中进行迭代?