使用ggplot2绘制箱线图时,如何保留因子的所有水平(含已过滤类别)
解决方法
核心问题是:过滤掉setosa后,Species的因子水平被自动删减,只剩versicolor和virginica,所以x轴不会显示setosa。要保留x轴位置,只要让Species的因子水平保持原始的三个,或者在ggplot里强制指定x轴刻度范围即可。
方法一:保留因子的所有原始水平
在过滤后,重新把Species设置为包含三个原始水平的因子,即使没有setosa的数据,因子水平依然存在,x轴就会保留该位置:
library(tidyverse) iris %>% filter(Species != "setosa") %>% # 重新指定因子水平为原始的三个 mutate(Species = factor(Species, levels = levels(iris$Species))) %>% ggplot(aes(x = Species, y = Sepal.Length, fill = Species)) + geom_boxplot()
方法二:在ggplot中强制指定x轴刻度范围
直接在scale_x_discrete里设置limits为原始的三个物种名称,不管数据里有没有对应值,x轴都会显示这些刻度:
library(tidyverse) iris %>% filter(Species != "setosa") %>% ggplot(aes(x = Species, y = Sepal.Length, fill = Species)) + geom_boxplot() + # 指定x轴刻度为所有原始物种 scale_x_discrete(limits = levels(iris$Species))
两种方法都能实现需求:x轴保留setosa的位置,同时只显示另外两个物种的箱线图。
内容的提问来源于stack exchange,提问作者Basil
相关产品推荐
相关产品推荐

