Search code examples
rggplot2geom-barx-axis

Plotting a Bar chart using ggplot2


I tried plotting a barchart with variables "week_day "from my dataframe. The variable contains days of the week. This is the code I used:

ggplot(data=df_activity)+geom_bar(mapping = aes(x=week_day,color=Totalhrs),fill= "blue")+
  labs(title ="Total Logins Across the Week") 

This is result I got.

click here. What do I do for the variable in X-axis to be arranged in order and not alphabetically?


Solution

  • You need to convert week_days to a factor and specify the order you want it to take:

    ggplot(df_activity) +
      geom_bar(aes(x = factor(week_day, levels = c("Monday", "Tuesday", "Wednesday", 
                              "Thursday", "Friday", "Saturday", "Sunday"))), 
                   fill = "blue") +
      labs(x = "Week day", title ="Total Logins Across the Week") 
    

    enter image description here


    Dummy data made up to match plot in question

    df_activity <- data.frame(
      week_day = rep(c("Monday", "Tuesday", "Wednesday", "Thursday", 
          "Friday", "Saturday", "Sunday"), 
        times = c(120, 150, 148, 145, 125, 123, 118))
    )