2015-10-15 51 views
0

我試圖構建一個圖表,除其他外,是按值而不是標籤排序的。然而,我發現沒有辦法一致地做到這一點 - 有時在圖表背後排序數據就足夠了,但大多數似乎沒有幫助。如何通過值而不是標籤對ggplot圖表進行排序?

它變得更糟,我想運行兩組圖表,理想情況下從同一個文件中爲每個圖表提取不同的點。

這裏有一個(簡化 - 真正的版本有值等幾種不同的列)版本的我的代碼:

library(ggplot2) 

texttable <- "CustomerID Level TerritoryID PointValue 
1 1 2 1.07008411325505 
2 1 6 0.818345721216575 
3 4 6 0.963128455248954 
4 1 6 1.00707326033957 
5 4 5 1.21104485305313 
6 5 1 0.997679907969959 
8 4 6 0.979654115606137 
9 4 6 1.06385914268472 
11 2 6 0.835519424818177 
12 4 3 0.868668911128272 
13 4 6 0.885912959934727 
14 6 6 1.132 
15 1 2 0.89646750726414 
16 5 1 1.21236715108711 
17 2 6 0.931486514531414 
18 2 2 1.03713079535294 
19 2 7 0.999841149204272 
20 1 4 0.946128993266485 
22 2 3 0.862294861210271 
23 2 6 0.82423674978601 
24 5 2 0.93637131146921 
27 2 1 0.992294385756429 
28 6 2 0.916891653017615 
30 4 2 1.02938833174225 
33 4 2 1.05472249469147 
34 3 2 0.910270389167454 
35 4 3 0.868004861090004 
36 1 1 1.00459731116181 
41 2 4 0.819587910554718 
42 2 3 0.774525504141426" 

datatable <- read.table(textConnection(texttable), header=TRUE) 
for (i in 1:nrow(datatable)) #Identify the categories as not numeric 
{ 
    datatable$CustomerID[i] <- toString(datatable$CustomerID[i]); 
    datatable$Level[i] <- toString(datatable$Level[i]); 
    datatable$TerritoryID[i] <- toString(datatable$TerritoryID[i]); 
} 

datatable <- datatable[order(datatable$PointValue),]; 

level1table <- subset(datatable, Level=="1") ; 
ggplot() + geom_point(aes(x=CustomerID, y=PointValue),data=level1table)+ggtitle("Level 1 PointValues"); 

territory6table <- subset(datatable, TerritoryID=="6") 
ggplot()+ geom_point(aes(x=CustomerID, y=PointValue),data=territory6table)+ggtitle("Territory 6 PointValues"); 

我應該怎麼做才能獲得積分出現在PointValue的順序?

+0

PointValue爲y; x是CustomerID,通過「Level」或「Territory」進行過濾。作爲最後一行的圖表幾乎是我想要的,除非它們沒有排序。我編輯了包含x =和y =的代碼,使其更清晰。 – Margaret

回答

1

reorder基於另一個序數的因子變量。

territory6table <- subset(datatable, TerritoryID=="6") 
territory6table$CID <- as.factor(territory6table$CustomerID) 
territory6table$CID <- reorder(territory6table$CID, territory6table$PointValue) 

ggplot()+ 
    geom_point(aes(CID, PointValue),data=territory6table)+ 
    ggtitle("Territory 6 PointValues") 

enter image description here

+0

您也可以在ggplot內執行重新排序:'aes(reorder(CID,Pointvalue),PointValue)'。 – eipi10

相關問題