rplot

Different plot for the same variable in R


I have a dataset like this:

a1 <- c("a","a","a", "b","b","b", "c", "c", "c", "d", "d", "d")
b1 <- c(7, 7, 7,5, 4, 4, 3, 3, 3, 3, 4, 6)
c1 <- c("1","2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12")

m1 <- data.frame(a1, b1, c1)

I want to plot this data and I want to plot Variable a1 and c1, but I want 4 different plot:

  1. for a1 = "a" --> x = 1, 2, 3 and y = 7, 7, 7, 5
  2. the same for "b" "c" and "d".

Basically, I want a plot for every different value in a1 variable, where x value are value in c1 and y value are value in a1.

How can I do?


Solution

  • As mentioned by qdread, sounds like you are looking for facet_wrap() (assuming c1 should be numeric)

    require(ggplot2)
    #> Loading required package: ggplot2
    a1 <- c("a","a","a", "b","b","b", "c", "c", "c", "d", "d", "d")
    b1 <- c(7, 7, 7,5, 4, 4, 3, 3, 3, 3, 4, 6)
    c1 <- c("1","2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12") |> as.numeric()
    
    m1 <- data.frame(a1, b1, c1)
    m1 |> 
      ggplot() + 
      aes(b1, c1) + 
      geom_point() + # switch geom_*() as needed, e.g. geom_line()
      facet_wrap(~a1)
    

    for a quick overview on ggplot2, you may have a look at the cheatsheet or at this introduction

    Created on 2024-09-23 with reprex v2.1.1