How can I plot line graphs running loops over columns?

Viewed 52

I am developing my skills to work on R as I am fairly new.

I have a data frame with n columns and n rows. I require to plot line graph (may be using ggplot), with the first column as x axis (it has Year Data) and running loops for rest of the columns. I need n-1 number of graphs for n column.

Let's say the data frame (df) has 5 columns of which the 1st will be used for x axis and loop should run 2 and onward. Values for the 2:5 columns will create line plots. Every new column should form a new graph representing values from respected cities. The below mentioned data frame, Followed by the code that I have been reading a lot about, resembles by data frame.

Year    C1  C2  C3  C4
2002    1   8   6   3
2003    5   2   6   5
2004    4   7   8   4
2005    5   1   1   2

I tried some codes similar to following but it did not extract any results.

for (i in 2:5) {
 ggplot(df......)
}

Please guide me through the process.

2 Answers

Do you mean this?

library(ggplot2)
# library(tidyr) # pivot_longer
ggplot(tidyr::pivot_longer(dat, -Year), aes(Year, value, color = name)) +
  geom_line()

ggplot2 plot with four lines

ggplot2 prefers its data in a "long" format. To see what I mean, look at the results post-pivot_longer:

tidyr::pivot_longer(dat, -Year)
# # A tibble: 16 x 3
#     Year name  value
#    <int> <chr> <int>
#  1  2002 C1        1
#  2  2002 C2        8
#  3  2002 C3        6
#  4  2002 C4        3
#  5  2003 C1        5
#  6  2003 C2        2
#  7  2003 C3        6
#  8  2003 C4        5
#  9  2004 C1        4
# 10  2004 C2        7
# 11  2004 C3        8
# 12  2004 C4        4
# 13  2005 C1        5
# 14  2005 C2        1
# 15  2005 C3        1
# 16  2005 C4        2

If you don't want to reshape, you have to do this another similar way:

gg <- ggplot(dat, aes(x = Year))
for (nm in names(dat)[-1]) {
  gg <- gg + geom_line(aes_string(y = nm, color = factor(nm)))
}
print(gg)

(But I recommend reshaping from wide to long. It enables a lot more than just this.)

(I will admit that one advantage to doing it with a for loop is that you can manually control the z-ordering, or which layer is "on top".)

If you prefer to learn the for loop and you want one plot per column you can do this (although it's brutal)...

library(ggplot2)
mydf <- data.frame(Year = c(2002:2005), C1 = c(1, 5, 4, 5), C2 = c(8, 2, 7, 1), C3 = c(6, 6, 8, 1), C4 = c(3, 5, 4, 2))
mydf  
#>   Year C1 C2 C3 C4
#> 1 2002  1  8  6  3
#> 2 2003  5  2  6  5
#> 3 2004  4  7  8  4
#> 4 2005  5  1  1  2


myaxis <- colnames(mydf[1])
mynames <- colnames(mydf[-1])
myaxis
#> [1] "Year"
mynames
#> [1] "C1" "C2" "C3" "C4"

for (i in seq_along(mynames)) {
  print(ggplot(mydf, aes_string(x = myaxis, y = mynames[[i]], group = 1)) + geom_line() + geom_point())
}

Created on 2020-05-12 by the reprex package (v0.3.0)

Related