ggplot:具有重复水平的因子的顺序

4

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

2
你只是没有正确使用 factor。你传递的级别必须始终是唯一的。你不应该只是将原始向量直接传递给级别参数。相反,你需要传递类似于 unique(df$season) 或按指定顺序排列的唯一值。 - joran
1个回答

8

为了有一个答案,这个可以正常工作:

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

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