R – Constructing a line graph using ggplot2

ggplot2r

I need to plot three lines (onto a single graph) each of which represents one lab team's data (two variables / team). Ideally, the graph should look aesthetically pleasing (hence the use of ggplot2!) yet similar in form to the line graphs shown below. I don't understand how to plot multiple lines onto a single graph using the gggplot2 library. My current knowledge of / skill with the ggplot2 library is low but I have included my fledgling efforts below.

http://www.harding.edu/fmccown/r/#linecharts

Edit: Each line is constructed from two vectors that look like this:

temp = c(4, 25, 50, 85, 100) 
enzyme_activity = c(0.543, 0.788, 0.990, 0.898, 0.882) 

with the temp variable on the x-axis and each line a different color so they can be differentiated.

Edit2:

amyA = c(0.091, 0.147, 0.202, 0.236, 0.074)
temp = c(4, 23, 37, 65, 100)
df = data.frame(temp, amyA)

ggplot(df, aes(x = temp, y = amyA, col = 'blue')) + geom_line()

The code within the second edit does not generate a blue line and the legend is completely wrong. If I repeat the two ggplot calls with differing data, only one line is plotted.

Best Answer

The key thing is to organize your data before plotting so as to have a factor column in the data frame indicating a separate line for each set of x, y values. For example:

set.seed(1)
df1 <- data.frame(e1 = sort(runif(5, 0.05, 0.25)),
                  e2 = sort(runif(5, 0.05, 0.25)),
                  e3 = sort(runif(5, 0.05, 0.25)),
                  t1 = sort(runif(5, 1, 100)),
                  t2 = sort(runif(5, 1, 100)),
                  t3 = sort(runif(5, 1, 100))
                  )
### reshape this to give a column indicating group
df2 <- with(df1,
        as.data.frame(cbind( c(t1, t2, t3),
                            c(e1, e2, e3),
                            rep(seq(3), each=5) )
                      ))
colnames(df2) <- c("temp","activity","team")
df2$team <- as.factor(df2$team)

Then

library(ggplot2)
ggplot(df2, aes(x=temp, y=activity, col=team)) + geom_line()

giving:enter image description here