Arrange days of the week on x axis while plotting

This is my code :

ggplot(data=daily_activity_new) +
geom_bar(aes(x=day_of_the_week)) +
labs(title="count of users logged in per day", x="Day of the week", y="frequency")

output : weekdays are displayed in the format 'Fri Mon Sat Sun thurs Tues Wed' on x axis

I want it to be displayed in either of the below formats

  1. In order sun mon tue etc
  2. desc based on count/frequency

I tried using fact() methods to reorder or arrange in desc but it's not working. the error says fact cant be applied on dataframe.

can anyone please help and let me know how to go about this?

1 Like

Hi, please put a reproducible example for better help all the community:
Copy and paste the result of run this:

dput(daily_activity_new[ 1:30,]  # check take all days

Im make a toy data:

library(tidyverse)
daily_activity_new <- data.frame(day_of_the_week=c("Saturday","Monday" ,"Thursday", "Wednesday",  "Friday", "Sunday"),
                                  freq=c(12,16,8,22,31,39))       

# For oder the days 
daily_activity_new$day_of_the_week <- factor(daily_activity_new$day_of_the_week, c("Monday", "Tuesday", "Wednesday", "Thursday","Friday","Saturday", "Sunday"))

ggplot(data=daily_activity_new) +
  geom_col(aes(x=day_of_the_week, y=freq)) +
  labs(title="count of users logged in per day", x="Day of the week", y="frequency")

image

Maybe is better if you put the data. Because if you want order by desc the frequency, so will change the days order.

Hey,

Thanks for your input. I have actually figured a way out to display it in asc or desc now. However unable to plot it in the order of days of the week. eg sun mon tue wed etc. Below is my modified code

ggplot(daily_activity_new, aes( x = reorder(day_of_the_week,day_of_the_week,function(x)-length(x)))) + geom_bar()

Before the plot you could set the order of days, like this :

# in this order appear in the plot.
daily_activity_new$day_of_the_week <- factor(daily_activity_new$day_of_the_week, c("Monday", "Tuesday", "Wednesday", "Thursday","Friday","Saturday", "Sunday"))
1 Like

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.