【问题标题】:ggplot: order of factors with duplicate levelsggplot:具有重复水平的因子的顺序
【发布时间】:2014-03-12 01:13:13
【问题描述】:

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) 之类的内容,或按指定顺序传递唯一值。

标签: r ggplot2


【解决方案1】:

所以这有一个答案,这很好用:

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

【讨论】:

    猜你喜欢
    • 2018-12-07
    • 2014-09-29
    • 1970-01-01
    • 2017-07-12
    • 2018-11-25
    • 2021-11-07
    • 2017-07-14
    • 2016-06-17
    • 1970-01-01
    相关资源
    最近更新 更多