2016-03-03 92 views
2

我試圖用ggplot做一個數據幀plot_data的barplot。在x軸上,我希望DestinationDuree_moy_trans(旅程的持續時間)排列,標籤的格式爲「Duration (Duree_moy_trans)」。 y軸應該是value,並且條應該用Categorie着色。根據ggplot中的變量重新排列x軸

我試圖使用reorder()來訂購x軸和scale_x_discrete()來設置標籤,但未能獲得所需的結果。我如何繪製這個情節?

這是數據,而我至今嘗試過的代碼:

plot_data= structure(list(Destination = structure(c(1L, 2L, 6L, 8L, 11L, 
12L), .Label = c("ABL", "ARP", "ATH", 
"BIE", "BOU", "BRE", "BRU", "BRI", 
"CHA", "CHE", "CHI", "CHO", 
"DOU", "EGL", "EPI", "ETA", "ETR", "GRA", 
"IVR", "JUV", "LAN", 
"LAR", "LES", "LEA", "LON", "MARO", 
"MAS", "MAS", "ORL", "PET", 
"PON", "RUN", "SAI", 
"SAM", "SAG", "SAV", 
"SER", "VER", "VIL", "VIT" 
), class = "factor"), Duree_moy_trans = c(15L, 36L, 28L, 44L, 
32L, 9L), Categorie = c("3", "3", "3", "3", "3", "3"), value = c(1, 
3, 2, 3, 1.33333333333333, 4)), .Names = c("Destination", "Duree_moy_trans", 
"Categorie", "value"), row.names = c(NA, 6L), class = "data.frame") 


library(ggplot2) 
ggplot(plot_data, aes(reorder(Duree_moy_trans, -value), y = value, 
     group= Categorie, fill = Categorie)) + 
    geom_bar(stat = "identity") + 
    scale_x_discrete(name = "Destination", 
        labels = paste(plot_data$Destination," (",plot_data$Duree_moy_trans,") ",sep="")) + 
    theme(plot.title = element_text(size=16,lineheight=2, face="bold")) + 
    scale_y_continuous(name=" Pourcentage %",limits = c(0,25)) 
+1

什麼是「我」和「DF」?你的例子遠非最小。去除不必要的東西,如標題和'theme()'(除非,當然,它們確實與你的問題有關)。確保您的代碼可以從乾淨的R會話中運行。 – Stibu

+1

對不起,現在我把最小的代碼,可以在一個乾淨的R會話中運行。謝謝 – ranell

+1

好多了,謝謝! – Stibu

回答

2

從你的問題,我不知道自己希望的順序是什麼:你說你要通過Duree_moy_trans訂購,但隨後在reorder()中使用-value。在下面,我會假設你想要訂購Duree_moy_trans

爲了獲得您想要的標籤(Destination (Duree_moy_trans)),我認爲在您繪製之前設置數據中的標籤會更容易。您可以在同一時間重新排序的因素:

new_dest <- paste0(plot_data$Destination, " (", plot_data$Duree_moy_trans, ")") 
plot_data$Destination <- reorder(new_dest, plot_data$Duree_moy_trans) 

然後你就可以用

ggplot(plot_data, aes(x = Destination, y = value, fill = Categorie)) + 
    geom_bar(stat = "identity") + 
    scale_y_continuous(name=" Pourcentage %",limits = c(0,25)) 

enter image description here

注意,你不需要group = Categorie繪製。

+0

這很完美!謝謝謝謝:) – ranell

+0

不客氣!你介意我是否稍微重新提出了你的問題以使其更清楚? – Stibu

+0

是的,你當然可以! – ranell