2

I have this table produced from a dataframe with 3 million observations.

    df_mc_day <- df_clean_distances %>% 
    mutate(weekday = factor(weekdays(df_clean_distances$started_at),levels=c("Monday", 
    "Tuesday", "Wednesday","Thursday", "Friday", "Saturday", "Sunday")), 
    mc=c(member_casual)) %>% tabyl(weekday, member_casual)
    df_mc_day %>% adorn_totals("row")
     weekday    casual  member
     Monday     147989  261391
     Tuesday    142020  278049
     Wednesday  154818  298865
     Thursday   162762  294189
     Friday     204401  299752
     Saturday   329738  316257
     Sunday     258167  259599
     Total     1399895 2008102

I want to make it into a chart that looks like this desired output chart

but I can only get ggplot to plot member or casual in two separate graphs. I know it has something to do with mutate but I don't understand what mutate is doing.


ggplot() + geom_col( data=df_mc_day, aes(x=weekday, y=member)) 
ggplot() + geom_col( data=df_mc_day, aes(x=weekday, y=casual)) 

Member only graph Casual only graph

1
  • 1
    With ggplot you need the data in long format i.e. df_mc_day %>% pivot_longer(cols = -weekday) %>% ggplot(aes(x = weekday, y = value, fill = name)) + geom_col(position = 'dodge') Commented Apr 26, 2021 at 21:44

2 Answers 2

1

Reshape the data into 'long' format with pivot_longer and use that in ggplot

library(dplyr)
library(tidyr)
library(ggplot2)
df_mc_day %>%
    pivot_longer(cols = -weekday) %>%
    ggplot(aes(x = weekday, y = value, fill = name)) + 
       geom_col(position = 'dodge') + 
       theme_bw()

data

df_mc_day <- structure(list(weekday = c("Monday", "Tuesday", "Wednesday", 
"Thursday", "Friday", "Saturday", "Sunday", "Total"), casual = c(147989L, 
142020L, 154818L, 162762L, 204401L, 329738L, 258167L, 1399895L
), member = c(261391L, 278049L, 298865L, 294189L, 299752L, 316257L, 
259599L, 2008102L)), class = "data.frame", row.names = c(NA, 
-8L))
Sign up to request clarification or add additional context in comments.

2 Comments

Wow, I have a ways to go but that worked perfectly. Thank you.
I can always learn a lot by looking at your answer only :) upvoted!
1

Here is a base R option with barplot

barplot(
  with(
    df_mc_day,
    t(`rownames<-`(cbind(casual, member), weekday))
  ),
  las = 2,
  beside = TRUE
)

which gives enter image description here

Comments

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.