将ggplot x轴上NA类别的位置更改

4

能否在 ggplot 的 x 轴上修改 NA 的位置?我已将 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


NA 更改为 "No Data" ,然后绘制图表? - zx8754
1个回答

3

要使用想要的顺序传递关卡到 scale_x_discretelimits 参数中:

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

以下是从scale_{x/y}_discrete文档中翻译得到的:

限制:一个字符向量,定义了刻度可能的值及其顺序。

enter image description here


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接