2

我无法弄清楚为什么 ggplot 重新排序我的分类变量

xaxis = c('80','90','100')
test = data.frame(x = xaxis, y = c(1,2,3))
ggplot(test, aes(x=x,y=y)) + geom_point()

在此处输入图像描述

我在网上发现它与因子水平有关,以下代码解决了我的问题。

xaxis = c('80','90','100')
xaxis = factor(xaxis,levels=xaxis)
test = data.frame(x = xaxis, y = c(1,2,3))
ggplot(test, aes(x=x,y=y)) + geom_point()

在此处输入图像描述

但是如果你回到原来的代码。

class(xaxis)
[1] "character"

它只是一个字符向量,我看不到任何先天排序。有人可以解释一下这里发生了什么吗?我是否总是必须将我的 x 变量更改为 ggplot 尊重我的序列的因素?

4

1 回答 1

2
sort(xaxis)
[1] "100" "80"  "90"

字符向量的排序是逐个字符完成的——即它不理解数据的数字上下文。

ggplot2将字符变量转换为因子,默认因子对其级别进行排序:

factor(xaxis)
[1] 80  90  100
Levels: 100 80 90
于 2013-10-31T09:11:44.300 回答