Home > Software design >  Sorting Ggplot columns
Sorting Ggplot columns

Time:10-05

Im trying to make a ggplot of a factor column and I want the plot to start from decreasing order of the highest count. I sorted my data before I plotted, but I still get the plot like this. Could someone please let me know how I can get a cleaner plot?enter image description here

library(viridis)
library(ggplot2)
library(tidyverse)

phenotype <- data.frame (table(tiering$Phenotype))
phenotype <- phenotype %>% rename(Phenotype = Varl, Total = Freg)
phenotype <- phenotype[order(phenotype$Total, decreasing = TRUE) ,]
P <- ggplot(phenotype, aes(Phenotype, Total, fill = Total))   geom_col()   geom_text(aes(label = Total), vjust=  0.3, size = 3.5)   theme classic()   ggtitle("Main phenotypes stated")  
scale_fill_viridis(option = "viridis")

enter image description here

CodePudding user response:

Here's a very quick way of doing it (where multiple solutions exist). Use factor to turn Phenotype into a factor and forcats::fct_inorder to arrange by the order you've already put them in.

On generated data:

library(tidyverse)
library(viridis)
#> Loading required package: viridisLite

tibble(Phenotype = sample(50:99, 50, replace = FALSE),
       Total = exp(rpois(50, 3))) |> 
  arrange(desc(Total)) |> 
  ggplot(aes(fct_inorder(factor(Phenotype)), Total, fill = Total))  
  geom_col()   
  theme_classic()   
  ggtitle("Main phenotypes stated")  
  scale_fill_viridis(option = "viridis")

Your question will perhaps be marked as a duplicate of Order discrete x scale by frequency/value asked 12 years ago - which posits quite a few ways of getting the outcome you need. Found by searching SO for ggplot2 tag

You can also arrange your columns within the ggplot(aes()) call with fct_reorder(factor(Phenotype), ...) like so:

phenotype |>
  ggplot(aes(fct_reorder(factor(Phenotype), Total, .desc = TRUE), Total, fill = Total))  
  geom_col()
  • Related