Search code examples
rplotggplot2r-factor

How to order factor variables in ggplot


I would like to order the plant growth form factor variables on the x-axis by decreasing slope value rather than alphabetically. I have tried the reorder() function but without success.

slope = c(1.0508194, 0.9406335, 1.1271495, 1.0496251, 
          0.9874658, 0.9358822, 0.8621570, 1.0403310, 
          1.0380560, 1.0401669)

veg3 <- data.frame(plant_growth_form = as.factor(c("fern", "fern ally", "grass", "herb","herbaceous climber", "herbaceous shrub",
                                                            "tree sapling", "undet", "woody climber", "woody shrub")))

ggplot(veg3, aes(x = plant_growth_form, y = slope)) +
   geom_point(cex=2) +
   xlab("Growth form") + ylab("Slopes") + ylim(0,2) +
   theme_bw() + theme(panel.grid.major = element_blank(), 
                      panel.grid.minor = element_blank())

A reproducible data subset generated with dput() can be found at: How to compute standard errors for predicted data


Solution

  • For me this code with reorder() works as expected.

    ggplot(veg3, aes(x = reorder(plant_growth_form,-slope), y = slope)) +
          geom_point(cex=2) +
          xlab("Growth form") + ylab("Slopes") + ylim(0,2) +
          theme_bw() + theme(panel.grid.major = element_blank(), 
                             panel.grid.minor = element_blank())