0

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?

Allan Cameron
  • 147,086
  • 7
  • 49
  • 87
Mimikul
  • 3
  • 1
  • Welcome! It is useful if you can make your example easily reproducible for others. Having an example of what "df_activity" contains will help people to answer you question. An easy way to generate the code to recreate this is using "dput". See the helpful hints here: https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example – David Aug 12 '22 at 18:21

1 Answers1

2

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))
)
Allan Cameron
  • 147,086
  • 7
  • 49
  • 87