Rearrange x axis according to a variable in ggplot

2019-05-23 14:09发布

问题:

I'm trying to do a barplot of a data frame plot_data with ggplot. On the x-axis, I want to have Destination ordered by Duree_moy_trans (duration of the trip) with labels of the form "Duration (Duree_moy_trans)". The y-axis should be value and the bars should be coloured by Categorie.

I have tried to use reorder() to order the x-axis and scale_x_discrete() to set the labels, but have failed to get the desired result. How can I draw this plot?

This is the data and the code that I have tried so far:

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:

From your question, I am not sure what the desired order is: you say you want to order by Duree_moy_trans, but then use -value in reorder(). In the following, I will assume that you want to order by Duree_moy_trans.

In order to have the labels you want (Destination (Duree_moy_trans)), I think it is easier to set the labels in the data before you plot. You can reorder the factor at the same time:

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

And then you can plot with

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

Note that you don't need group = Categorie.



标签: r ggplot2