在ggplot x轴上改变NA类别的位置

问题描述 投票:3回答:1

是否有可能在NA的x轴上改变ggplot的位置?下面我将NA水平设置在因子水平的第二个位置,但是NA仍然出现在x轴的最后位置。

library(ggplot2)

dat <- iris[c(1,2,51,52,101,102),]
dat[1,"Species"] <- NA
dat[["Species"]] <- factor(dat[["Species"]], 
                           levels = c("virginica", NA, "setosa", "versicolor"), 
                           exclude = NULL)
dat[["Species"]]
# [1] <NA>       setosa     versicolor versicolor virginica  virginica 
# Levels: virginica <NA> setosa versicolor
# NA is the second level

ggplot(dat, aes(x=Species, y=Sepal.Width)) + geom_point()
# NA appears at right

enter image description here

r ggplot2
1个回答
3
投票

要使用所需的订单通过级别到scale_x_discrete limits参数:

library(ggplot2)
ggplot(dat, aes(Species, Sepal.Width)) + 
    geom_point() +
    scale_x_discrete(limits = levels(dat$Species))

来自scale_{x/y}_discrete文档:

limits:一个字符向量,用于定义可能的比例值及其顺序。

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.