0

I have a dataset like below

# # A tibble: 94 × 4
#    type          shortcut    date              time
#    <chr>         <chr>       <date>            <dbl>         
#  1 Three lap      No         2010-08-17         24.24                          
#  2 Three lap      No         2010-08-24         38                             
#  3 Three lap      Yes        2010-08-31         32.4                             
#  4 Single lap     No         2010-09-07         20.6                           
#  5 Single lap     No         2010-09-14         39.03                          

And I want to reproduce the plot as in the photo enter image description here

I don't know how to recreate the "Race" variable as in the graph. I tried this but it doesn't work!

newdata <- records %>%
 group_by(type, shortcut) %>%
 mutate(race = case_when( 
                 type == "Three lap" && shortcut == "No" ~ "Three lap with no shortcut",
                 type == "Three lap" && shortcut == "Yes" ~ "Three lap with shortcut",
                 type == "Single lap" && shortcut == "No" ~ "Single lap with no shortcut",
                 type == "Single lap" && shortcut == "Yes" ~ "Single lap with shortcut")) 

ggplot(data = newdata, mapping = aes(x = date, y = time, color = race)) +
  geom_line() + 
  geom_point()

Any suggestions on what I should try?

  • 1
    It's easier to help you if you make your question reproducible by including data in a useable format eg paste the output of `dput(records)` into the question to enable testing and verification of possible solutions. [Link for guidance on asking questions](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) – Peter Sep 24 '21 at 08:38

1 Answers1

0

Use & instead of && as && is for scalars. Also you don't need group_by here.

Try -

library(dplyr)
library(ggplot2)

records %>%
  mutate(race = case_when( 
    type == "Three lap" & shortcut == "No" ~ "Three lap with no shortcut",
    type == "Three lap" & shortcut == "Yes" ~ "Three lap with shortcut",
    type == "Single lap" & shortcut == "No" ~ "Single lap with no shortcut",
    type == "Single lap" & shortcut == "Yes" ~ "Single lap with no shortcut",
    TRUE ~ "Single lap with shortcut"))  %>%
  ggplot(aes(x = date, y = time, color = race)) +
    geom_line() + 
    geom_point()
Ronak Shah
  • 377,200
  • 20
  • 156
  • 213
  • Hi @Ronak Shah , I've tried the code and there's an error message: "Error: Must request at least one colour from a hue palette." ? I'm not sure why I need to specify a color? – Thuy Nguyen Sep 24 '21 at 09:47
  • Sorry, I did not add a space in Threelap and other values. Try the updated answer which has space between Three and lap. – Ronak Shah Sep 24 '21 at 10:04