2013-11-27 129 views
1

我試圖繪製旅行長度分佈(每隔10英里增加距離我想查找該特定年份的該行程的百分比)。當我將它繪製在ggplot2中時,我的X軸刻度標籤按字母順序排列,而不是按照距離的增加順序排列。我曾嘗試使用建議的各種技巧(Change the order of a discrete x scale),但沒有獲得任何地方。一個鏈接我的代碼如下,數據集在這裏(http://goo.gl/W1jjfL)。如何重新排列ggplot2中的字符串X軸刻度標籤

library(ggplot2) 
library(reshape2) 

nwpt <- subset(nonwork, select=c(Distance, PersonTrips1995, PersonTrips2001, PersonTrips2009)) 
nwpt <- melt(nwpt, id.vars="Distance") 

ggplot(data=nwpt, aes(x=Distance, y=value, group=variable, colour=variable)) + scale_x_discrete(name="Distance") + geom_line(size=0.5) + ggtitle("Non Work Person Trips") + ylab("Percent") 

我檢查以查看是否距離變量是一個因素,它是如下所示:

is.factor(nwpt $距離)1 TRUE

然而,我得到的輸出不是我想要的。而不是10英里以下的第一類,10-14英里是下一個等我得到的情節如下所示(PDF格式在這裏:http://goo.gl/V7yvxT)。

enter image description here

任何幫助表示讚賞。 TIA 克里希南

+0

重新排序因子水平。我認爲'gdata'包中的'reorder.factor()'函數會自動執行你所需要的。 –

回答

2

這裏有一種方法:

library(ggplot2) 
library(reshape2) 

nwpt <- subset(nonwork, 
       select=c(DID,Distance,PersonTrips1995,PersonTrips2001,PersonTrips2009)) 
nwpt <- melt(nwpt, id.vars=c("DID","Distance")) 

ggplot(data=nwpt, aes(x=DID, y=value, colour=variable)) + 
    geom_line(size=0.5) + 
    labs(title="Non Work Person Trips", y="Percent") + 
    scale_x_discrete(name="Distance", labels=nwpt$Distance) + 
    theme(axis.text.x=element_text(angle=90)) 

生成此與您的數據集: