如何在ggplot2的facet_wrap中排除hermaphroditic和none类别?
解决ggplot2分面排除指定类别的问题
要在分面中排除hermaphroditic和none这两个类别,核心是先过滤对应数据行或在分面时指定子集,以下是两种可行方案:
方案一:提前过滤数据集
用dplyr包的filter()函数先筛选出需要的类别,再绘图:
library(ggplot2) library(dplyr) # 过滤掉不需要的sex类别 starwars_filtered <- starwars %>% filter(!sex %in% c("hermaphroditic", "none")) # 绘制分面密度图 ggplot(starwars_filtered, aes(x = height)) + geom_density(fill = "skyblue") + theme_bw() + facet_wrap(~ sex, scales = "free_y")
方案二:在分面时直接指定子集
无需提前处理数据集,直接在facet_wrap()中使用subset参数过滤:
library(ggplot2) ggplot(starwars, aes(x = height)) + geom_density(fill = "skyblue") + theme_bw() + facet_wrap(~ sex, scales = "free_y", subset = !sex %in% c("hermaphroditic", "none"))
额外提示
你原代码中aes(x=height, fill=sex)的fill映射没有生效,因为geom_density()里直接硬编码了fill="skyblue"。如果需要按sex区分填充色,可以去掉geom_density()中的fill参数,再加个透明度让图形更清晰:
ggplot(starwars_filtered, aes(x = height, fill = sex)) + geom_density(alpha = 0.7) + theme_bw() + facet_wrap(~ sex, scales = "free_y")
内容的提问来源于stack exchange,提问作者AgentCircus
相关产品推荐
相关产品推荐

