2012-03-06 5 views
1

他のファクタのレベルの一致する順序に従って、1つのdata.frame列のファクタのレベルを並べ替えるにはどうすればよいですか?コードの例ではR - 1つのファクタ(ggplotでのラベル付けのため)別のファクタの並べ替え

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") 

Iは、DFの$ラウンド順序(番号順)に従って順序付けDF $レース係数を用いて、X軸のラベルのセットを生成することができる方法は?つまり、+scale_x_discrete(labels=df$race)をggplotコマンドに追加すると、x軸ラベルが元のx軸df $ round値の順序に従うようにするにはどうすればよいですか?

+1

'relevel()'または 'reorder()' – Chase

答えて

1

あなたのデータフレームがすでにソートされ、レースは文字で、あなたは少しカンニングしてこれを行うことができる場合:

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)) 

チェイスが言うようにそれ以外の場合は、relevelreorderは、移動するための方法です。

関連する問題