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()
factor
。你传递的级别必须始终是唯一的。你不应该只是将原始向量直接传递给级别参数。相反,你需要传递类似于unique(df$season)
或按指定顺序排列的唯一值。 - joran