'How to make multiple smooth curves in one plot in R (with these data)?

I am a beginner with R. I have the next data: 5 cars drive from A to B, the total distance is 100 km. The speed of these cars is measured during different moments. On the x-axis the moment of measuring (in km) and on y-axis the speed at that moment.

I sorted my data in excel as on the picture: Excelsheet.

I tried to plot these data with ggplot, but I didn't get any line and if I get lines, than they are not smooth. Also I want points at the place of measurements and give them a colour. And put a legenda next to it, like on the picture. On excel it is easy, but as beginner in R it is difficult. I tried already different methods.

Could anyone help me please?

Second measurement data



Solution 1:[1]

Most of the work is in the data munging. The plotting itself is straightforward.

# Data munging
tribble(~"Km1",~"Speed1",~"Km2",~"Speed2",~"Km3",~"Speed3",
        10,32,8,64,5,34,
        20,63,15,34,15,23,
        30,45,26,46,25,55,
        40,45,37,75,35,64,
        
        50,1,50,2,50,3) %>% 
  tidyr::pivot_longer(cols = everything(),names_to = "Name",values_to = "Values") %>% 
  dplyr::mutate(Car = str_extract(Name,"\\d") %>% str_c("Car ",.),
                Name = str_replace(Name,"\\d","")) %>% 
  dplyr::group_by(Car,Name) %>% 
  dplyr::mutate(Values = str_c(Values,collapse = ",")) %>% 
  dplyr::slice(1) %>% 
  dplyr::ungroup() %>% 
  tidyr::pivot_wider(id_cols = Car,names_from = Name,values_from = Values) %>% 
  tidyr::separate_rows(Km, Speed) %>% 
  dplyr::mutate(Km = as.numeric(Km),
                Speed = as.numeric(Speed)) 
  # Data plotting
  ggplot(aes(Km,Speed,color = Car)) +
  geom_point() + 
  stat_smooth()

Output:

enter image description here

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1