我試圖用ggplot做一個數據幀plot_data
的barplot。在x軸上,我希望Destination
按Duree_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))
什麼是「我」和「DF」?你的例子遠非最小。去除不必要的東西,如標題和'theme()'(除非,當然,它們確實與你的問題有關)。確保您的代碼可以從乾淨的R會話中運行。 – Stibu
對不起,現在我把最小的代碼,可以在一個乾淨的R會話中運行。謝謝 – ranell
好多了,謝謝! – Stibu