psychemedia
psychemedia

Reputation: 5940

R - Reordering One Factor (for labeling purposes in ggplot) by another

How can I order the levels of a factor in one data.frame column according to the coincident order of levels of another factor?

For example, in the code:

require(RJSONIO)
require(ggplot2)

race.data.json=fromJSON('http://ergast.com/api/f1/2011/constructors/mclaren/results.json?limit=50')

pd=function(rd,df=NULL) {
  for (el in rd$MRData$RaceTable$Races)
    for (el2 in el$Results){ 
      tmp=data.frame(row.names=NULL,round=as.numeric(el$round),race=el$raceName,num=el2$number,pos=el2$position,driver=el2$Driver['familyName'])
      df=rbind(df,tmp)
    }
  df
}
df=pd(race.data.json)

df$pos=factor(df$pos,levels=c('1','2','3','4','5','6','7','8','9','10','11','12','13','14','15','16','17','18','19','20','21','22','23','24','DNF') )

ggplot(df)+geom_point(aes(x=round,y=pos,col=driver))+scale_colour_discrete(name="Driver")

how can I generate a set of x-axis labels using the df$race factor ordered according to the df$round order (numerical order)? That is, if I add +scale_x_discrete(labels=df$race) to the ggplot command, how can I ensure that the x-axis labels follow the order of the original x-axis df$round values?

Upvotes: 1

Views: 561

Answers (1)

joran
joran

Reputation: 173517

If your data frame is already sorted, and race is a character, you can cheat a little and do this:

ggplot(df)+geom_point(aes(x=factor(round),y=pos,col=driver)) + 
    scale_colour_discrete(name="Driver") + 
    opts(axis.text.x = theme_text(angle = 90)) + 
    scale_x_discrete(labels = unique(df$race))

Otherwise, relevel and reorder are the way to go, as Chase says.

Upvotes: 1

Related Questions