kaix
kaix

Reputation: 305

How do I chart a new graph for multiple columns where there are 2 series for Y

I have a dataset df1. I would like to chart a line graph with Date as X and Chart1 and T1. I would like to loop it for all column where I would get the same graph when Y is Chart2 and T2 as well as when Y is Chart3 and T3.

dput(df1) >
structure(list(Date = c(1990, 1991, 1992, 1993, 1994), Chart1 = c(25, 
34, 19, 7, 4), T1 = c(23.5, 23.5, 23.5, 23.5, 23.5), Chart2 = c(2, 
4, 12, 9, 15), T2 = c(10, 10, 10, 10, 10), Chart3 = c(11, 9, 
8, 6, 2), T3 = c(5, 5, 5, 5, 5)), row.names = c(NA, -5L), class = c("tbl_df", 
"tbl", "data.frame"))

This is the chart that I would like to get for each column (Chart2,T2) and (Chart3,T3) etc. ggplot(df1, aes(x=Date)) + geom_line(aes(y=Chart1)) + geom_line(aes(y=T1), color="red")

enter image description here

Upvotes: 0

Views: 25

Answers (1)

Ronak Shah
Ronak Shah

Reputation: 388982

You may separate out 'Chart' variables and 'T' variables and create list of plots.

library(ggplot2)

chart_cols <- grep('Chart', names(df1), value = TRUE)
t_cols <- grep('T\\d+', names(df1), value = TRUE)

list_plots <- Map(function(x, y) ggplot(df1, aes(x=Date)) + 
  geom_line(aes(y=.data[[x]])) +  
    geom_line(aes(y=.data[[y]]), color="red"), chart_cols, t_cols)

Upvotes: 1

Related Questions