根据ggplot

时间:2016-03-03 13:24:02

标签: r ggplot2

我试图用ggplot做一个数据框plot_data的条形图。在x轴上,我希望DestinationDuree_moy_trans(行程的持续时间)排序,并带有#34; Duration (Duree_moy_trans)"形式的标签。 y轴应为value,条形应按Categorie着色。

我尝试使用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 个答案:

答案 0 :(得分:2)

根据您的问题,我不确定所需的订单是什么:您说要按Duree_moy_trans订购,然后在-value中使用reorder()。在下文中,我假设您要按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