gpt4 book ai didi

r - ggplot 重新排序分类变量

转载 作者:行者123 更新时间:2023-12-05 05:27:22 24 4
gpt4 key购买 nike

我无法弄清楚为什么 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()

enter image description here

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

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()

enter image description here

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

class(xaxis)
[1] "character"

它只是一个字符向量,我看不到任何固有的顺序。有人可以解释这里发生了什么吗?我是否总是必须将我的 x 变量更改为一个因子,以便 ggplot 遵守我的序列?

最佳答案

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

字符向量的排序是逐个字符进行的 - 即它不理解数据的数字上下文。

ggplot2 会将字符变量转换为因子,默认情况下因子对它们的级别进行排序:

factor(xaxis)
[1] 80 90 100
Levels: 100 80 90

关于r - ggplot 重新排序分类变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19701894/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com