如何解决在散点图中标记 2 个变量
library(ggplot2)
library(dplyr)
#install.packages("ggrepel")
library(ggrepel)
#Code
mpg %>%
mutate(Color=ifelse(class == '2seater','2seater','Other')) %>%
ggplot(aes(displ,hwy,colour = Color)) +
geom_point() +
geom_text_repel(aes(label = ifelse(Color == '2seater',"")),force_pull = 0,show.legend = FALSE) +
theme(legend.position = "none")
在上面的代码中,如果我想为“紧凑”添加另一个标签,我将如何更改代码,所以我想要 2 个标签 - 一个用于紧凑型和 2 座
解决方法
您可以在使用 case_when
的地方使用 if else
。 [虽然您可以在另一个 ifelse
中使用 ifelse
。但我觉得 case_when
更干净。]
但是看看。标签是不是太多了?为什么不直接用颜色编码?
library(ggplot2)
library(dplyr)
library(ggrepel)
#Code
ggplot2::mpg %>%
mutate(Color = case_when(
class == "2seater" ~ "2seater",class == "compact" ~ "compact",TRUE ~ "other"
)) %>%
ggplot(aes(displ,hwy,colour = Color)) +
geom_point() +
geom_text_repel(aes(
label =
case_when(
class == "2seater" ~ "2seater",class == "compact" ~ "compact"
)
),force_pull = 0,show.legend = FALSE
) +
scale_color_manual(values = c("red","blue","gray")) +
theme(legend.position = "none")
,
作为 MarBlo 提出的 case_when()
方法的替代方法,您还可以在指定层的同时对数据进行子集化。优点是写得更短,缺点是标签不会排斥未标记的点。正如 MarBlo 所提到的,ggrepel 抗议标签可能太多。
library(ggplot2)
library(dplyr)
library(ggrepel)
mpg %>%
mutate(Color=ifelse(class == '2seater','2seater','Other')) %>%
ggplot(aes(displ,colour = Color)) +
geom_point() +
geom_text_repel(aes(label = class),data = ~ subset(.,class %in% c("2seater","compact")),show.legend = FALSE) +
theme(legend.position = "none")
#> Warning: ggrepel: 31 unlabeled data points (too many overlaps). Consider
#> increasing max.overlaps
由 reprex package (v0.3.0) 于 2021 年 1 月 10 日创建
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。