Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ggplot: order of factors with duplicate levels

Tags:

r

ggplot2

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()
like image 374
user3408551 Avatar asked Oct 15 '25 13:10

user3408551


1 Answers

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()
like image 50
joran Avatar answered Oct 18 '25 03:10

joran



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!