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?

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: stackoverflow.com/questions/5963269/… Commented Aug 12, 2022 at 18:21

1 Answer 1

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))
)
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you very Much, I changed the week_day variable to Factor and it worked perfectly

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.