4

ggplot changes the order of an axis variable, which I do not want. I know I can change the variable to a factor and specify the levels to get around this, but what if the levels contain duplicate values?

An example is below. The only alternative I can think of is to use reorder(), but I can't get that to preserve the original order of the variable.

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()
joran
  • 169,992
  • 32
  • 429
  • 468
user3408551
  • 41
  • 1
  • 2
  • 2
    You're just not using `factor` correctly. The levels you pass always need to be unique. You should never just pass the raw vector to the levels argument. Instead, you would pass it something like `unique(df$season)`, or the unique values in a specified order. – joran Mar 12 '14 at 01:45

1 Answers1

8

Just so this has an answer, this works just fine:

df$season2 <- factor(df$season, levels=unique(df$season))
ggplot(df, aes(x=season2, y=temp, colour=type, group=type)) + 
   geom_point() + 
   geom_line()
joran
  • 169,992
  • 32
  • 429
  • 468