Search code examples
rplotscatter-plot

Plot multiple lists on the same graph in r (scatter plot)


I was trying to plot a graph that looks like the below figure based on the code under it:

Figure

xAxisName <- c("ML", "MN")

car1 <- c(5,6)
names(car1) <- xAxisName
car2 <- c(5.5,6.2)
names(car2) <- xAxisName
car3 <- c(4.9, 5.4)
names(car3) <- xAxisName

The plot plots 2 car properties on the x axis and each property has 3 car values. But these are separate lists. How could this plot be plotted?


Solution

  • Get all the 'car' objects into a list, bind them with bind_rows and use ggplot, then pivot to 'long' format and use ggplot

    library(ggplot2)
    library(dplyr)
    library(tidyr)
    mget(ls(pattern = '^car\\d+$')) %>%
         bind_rows(.id = 'car') %>% 
         pivot_longer(cols = -car) %>% 
         ggplot(aes(x = name, y = value, color = car)) +
            geom_point()+ 
         scale_y_continuous(expand = c(5, 6))