Help with ggplot

Hello
I'm beggining with ggplot and I need to make a line plot using this data
image
I want a line chart for the average duration for every week day, one line for members, and other for casual riders. This is the code I have so far:

mean_by_day_casual %>% ggplot(aes(x=day_of_week)) +
geom_line(aes(y=member)) +
geom_line(aes(y=casual))

and I get this error and an empty chart:

geom_path: Each group consists of only one observation. Do you need to adjust the
group aesthetic?
geom_path: Each group consists of only one observation. Do you need to adjust the
group aesthetic?

Anybody knows what can I do to fix this?

The tidyverse prefers that your data be structured a certain way, and the data you have isn't quite there, but it's an easy fix. You have three variables (weekday, user type, and duration) and you should have one column holding each. This is easy to do with pivot_longer - I'll use a subset of your data to illustrate.

library(tidyverse)

df <-  tribble(
  ~day_of_week, ~member, ~casual,
  "Monday", 13.85, 30.4,
  "Tuesday", 13.66, 27.9,
  "Wednesday", 13.7, 27.1
)

df %>%
  pivot_longer(c(member, casual), names_to = "type", values_to = "duration")

# A tibble: 6 × 3
  day_of_week type   duration
  <chr>       <chr>  <dbl>
1 Monday      member  13.8
2 Monday      casual  30.4
3 Tuesday     member  13.7
4 Tuesday     casual  27.9
5 Wednesday   member  13.7
6 Wednesday   casual  27.1

Once you have that, a line plot will group observations into separate lines using the group aesthetic. In the code below, using type as the group means that all the observations with type "member" make up one line, and similarly with "casual".

df %>%
  pivot_longer(c(member, casual), names_to = "type", values_to = "duration") %>%
  ggplot(aes(day_of_week, duration, color = type, group = type)) +
  geom_line()

Hope that helps!

1 Like

Thanks a lot! :smiley:
That solved the problem

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.