gpt4 book ai didi

r - ggplot : order of factors with duplicate levels

转载 作者:行者123 更新时间:2023-12-04 00:43:56 24 4
gpt4 key购买 nike

ggplot 更改了我不想要的轴变量的顺序。我知道我可以将变量更改为一个因子并指定级别来解决这个问题,但是如果级别包含重复值怎么办?

下面是一个例子。我能想到的唯一选择是使用 reorder() ,但我无法保留变量的原始顺序。

require(ggplot2)
season <- c('Sp1', 'Su1', 'Au1', 'Wi1', 'Sp2', 'Su2', 'Au2', 'Wi2', 'Sp3', 'Su3', 'Au3', 'Wi3') # this is the order I want the seasons to appear in
tempa <- rnorm(12, 15)
tempb <- rnorm(12, 20)

df <- data.frame(season=rep(season, 2), temp=c(tempa, tempb), type=c(rep('A',12), rep('B',12)))


# X-axis order wrong:
ggplot(df, aes(x=season, y=temp, colour=type, group=type)) + geom_point() + geom_line()

# X-axis order correct, but warning of duplicate levels in factor
df$season2 <- factor(df$season, levels=df$season)
ggplot(df, aes(x=season2, y=temp, colour=type, group=type)) + geom_point() + geom_line()

最佳答案

就这样这有一个答案,这很好用:

df$season2 <- factor(df$season, levels=unique(df$season))
ggplot(df, aes(x=season2, y=temp, colour=type, group=type)) +
geom_point() +
geom_line()

关于r - ggplot : order of factors with duplicate levels,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22340053/

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