即使所有组都为空,也显示空组

sin*_*dur 2 r ggplot2

使用scale_x_discrete(drop = FALSE)I 设法将空组保持在 x 轴上的位置:

library(ggplot2)
iris_filtered <- subset(iris, Sepal.Length > 7)
ggplot(data = iris_filtered, mapping = aes(x = Species, y = Sepal.Width)) +
  geom_boxplot() +
  scale_x_discrete(drop = FALSE)
Run Code Online (Sandbox Code Playgroud)

在此处输入图片说明

除非所有组都为空,否则我得到:

iris_filtered <- subset(iris, Sepal.Length > 8)
ggplot(data = iris_filtered, mapping = aes(x = Species, y = Sepal.Width)) +
  geom_boxplot() +
  scale_x_discrete(drop = FALSE)
Run Code Online (Sandbox Code Playgroud)

在此处输入图片说明

我希望的输出是:

在此处输入图片说明

Dom*_*ier 5

您可以只指定 x 轴限制:

iris_filtered <- subset(iris, Sepal.Length > 8)
ggplot(data = iris_filtered, mapping = aes(x = Species, y = Sepal.Width)) +
  geom_boxplot() +
  scale_x_discrete(drop = FALSE, limits = unique((iris$Species))

Run Code Online (Sandbox Code Playgroud)

在此处输入图片说明

显示 y 轴比例的类似方法:

ggplot(data = iris_filtered, mapping = aes(x = Species, y = Sepal.Width)) +
  geom_boxplot() +
  scale_x_discrete(drop = FALSE, limits = c("a","b","c")) +
  ylim(min(iris$Sepal.Length), max(iris$Sepal.Length))
Run Code Online (Sandbox Code Playgroud)

在此处输入图片说明