Home > Mobile >  Plotting a line plot in ggplot using corresponding vector inputs as x and y variables
Plotting a line plot in ggplot using corresponding vector inputs as x and y variables

Time:12-12

I post a reproducible example below:

a<-runif(10,5,20)
b<-runif(10,2,11)
c<-runif(10,12,27)
d<-runif(10,19,38)
e<-runif(10,4,15)
q<-runif(10,11,26)


df<-data.frame(A=a,B=b,C=c,D=d,E=e,Q=q)


vec1<-c("Q","A","B","C","D","D","E")
vec2<-c("A","B","C","D","E","Q","B")

I would like to produce multiple ggplot line charts using a loop through the data frame df, with the x and y variables being from vec1 and vec2.

For example, the first chart should be Q vs A, second A vs B.........last being E vs B.

Thank you

CodePudding user response:

You can use Map to create a ggplot object from each pair of columns:

library(ggplot2)

plot_list <- Map(function(A, B) {
  ggplot(data.frame(x = df[[A]], y = df[[B]]), aes(x, y))  
    geom_line()  
    labs(x = A, y = B)
 }, A = vec1, B = vec2)

This results in a list of ggplot objects. For example, you can get the first one like this:

plot_list[[1]]

enter image description here

And the second like this:

plot_list[[2]]

enter image description here

Or you can plot them all on the same page like this:

ggpubr::ggarrange(plotlist = plot_list)

enter image description here

Created on 2022-12-12 with reprex v2.0.2

  • Related