Reordering variables on x axis as in data frame

Hi, I have a data frame but the variables are plotted in alphabetical order on x axis as below:
image
, but I would like them to appear as in a data frame. This is my reprex. Thanks
library(dplyr)

library(tidyr)
library(ggplot2)
library(forcats)
df <- data.frame(

  • id = c(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13),
  • Urban = c(3, 3, 3, 4, 3, 3, 3, 3, 2, 3, 4, 3, 2),
  • Low_land = c(4, 3, 4, 3, 4, 3, 3, 4, 2, 4, 3, 3, 3),
  • Agricultural = c(4, 3, 4, 4, 4, 3, 4, 4, 2, 4, 4, 4,3),
  • Wetland = c(4, 3, 4, 3, 3, 2, 4, 4, 2, 4, 4, 4, 3),
  • Others = c(2, 3, 3, 3, 3, 3, 3, 1, 3, 3, 4, 3, 2)
  • )

df %>%

  • gather(variable, category, -id) %>%
    
  • filter(!is.na(category)) %>% 
    
  • count(variable, category) %>% 
    
  • ggplot(aes(x = variable,
    
  •            y = n,
    
  •            fill = factor(category, labels = c("Not Sensitive", "Slightly Sensitive", "Sensitive", "Very Sensitive")))) + 
    
  • geom_col() + 
    
  • labs(x = "Sensitivity",
    
  •      y = "Count",
    
  •      fill = "Category") +
    
  • theme(axis.text.x = element_text(angle=30, hjust=1, vjust = 1))

You can do that by adding

scale_x_discrete(limits = c("Urban","Low_land", "Agricultural", "Wetland","Others")) 

So the whole code will look like this:

d <- df %>%
  gather(variable, category, -id) %>%
  filter(!is.na(category)) %>% 
  count(variable, category)
  
ggplot(data = d, aes(x = variable,
             y = n,
             fill = factor(category, labels = c("Not Sensitive", "Slightly Sensitive", "Sensitive", "Very Sensitive")))) + 
  geom_col() + 
  labs(x = "Sensitivity",
       y = "Count",
       fill = "Category") +
  scale_x_discrete(limits = c("Urban","Low_land", "Agricultural", "Wetland","Others"))+
  theme(axis.text.x = element_text(angle=30, hjust=1, vjust = 1))

Great thanks for this task. It's fine now.

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.