R; geom_area, order according to numeric variable

Viewed 413

I am trying to make a ggplot with geom_area, where the order for stacking the layers should follow the entries of a numeric variable. In fact, in my case, I would like this variable to be the standard deviation for each category, such that the more constant categories are in the bottom of the plot, and the most variable ones at the top.

Here is what I wrote for this simple expample:

dx <- data.frame(x=rep(1:8,3),y=rep(c(2,3,2,4,3,5,3,2,2,3,2,4,3,50,3,2,2,3,2,4,3,20,3,2)),z=c(rep("bread",8),rep("butter",8),rep("fish",8)), 
             zz=c(rep(1,8),rep(3,8),rep(2,8)))
dx_sd <- aggregate(dx$y, by = list(dx$z), FUN = sd)

for (i in 1:nrow(dx_sd)){
dx$sd[dx$z == dx_sd$Group.1[i]] <-
dx_sd$x[i]}

dx <- dx[order(-dx$sd),]
ggplot() + geom_area(data=dx, aes(x=x, y=y, fill=z))

In the following image, I want bread to be at the bottom, fish in the middle, and butter at the top.

wrong plot

I would be very grateful if someone could help me solve this issue. Thank you very much in advance.

1 Answers
Related