Using R and ggplot, how would I plot data with 3 x variables that all have multiple time values

Viewed 41

so I am new to R and I am having trouble on figuring out how I would plot this data. I guess I am confused on how to use the aes function in ggplot, because I do not understand how I would categorize the x and y if I have 3 columns of data with a bunch of various times beneath each.

Grubhub Postmates Doordash
    2       4         5
    5       8         9 
    2       2         8
    29      8         17
    12      23        98

I am trying to achieve this result:

the end goal

How would I use ggplot to do this? I am so lost, thank you!

1 Answers

The key is to format data to long. One good practice in ggplot2 is to reshape data so that all aesthetics devices can work well. You data is in format known as wide. In order to transform it you can use tidyverse functions like pivot_longer() and everything() to adjust the format of your data. With that done, you can sketch the plot as seen in the code. Here the solution:

library(tidyverse)
#Code to reshape data to long
df %>% pivot_longer(everything()) %>%
  ggplot(aes(x=name,y=value,color=name,group=name))+
  geom_point()

Output:

enter image description here

Some data used:

#Data
df <- structure(list(Grubhub = c(2L, 5L, 2L, 29L, 12L), Postmates = c(4L, 
8L, 2L, 8L, 23L), Doordash = c(5L, 9L, 8L, 17L, 98L)), class = "data.frame", row.names = c(NA, 
-5L))

Ans if you want to remove the legend, you can adjust the theme() option:

#Code to reshape data to long 2
df %>% pivot_longer(everything()) %>%
  ggplot(aes(x=name,y=value,color=name,group=name))+
  geom_point()+
  theme(legend.position = 'none')

Output:

enter image description here

Related