0

I can't seem to figure out how to create a graph for multiple line plots.

This is my dataframe:

   topics before_event after_event current
1       1        0.057       0.044   0.064
2       2        0.059       0.055   0.052
3       3        0.058       0.037   0.044
4       4        0.036       0.055   0.044
5       5        0.075       0.064   0.066
6       6        0.047       0.045   0.045
7       7        0.043       0.043   0.041
8       8        0.042       0.041   0.046
9       9        0.049       0.046   0.039
10     10        0.043       0.060   0.045
11     11        0.054       0.054   0.062
12     12        0.065       0.056   0.068
13     13        0.042       0.045   0.048
14     14        0.067       0.054   0.055
15     15        0.049       0.052   0.053

The variables in the dataframe are all numeric vectors, example:

topics <- c(1,2,3,4,5,6,7,8,9,10,11,12,13,14,15)

I know I should be using 'ggplot2' and 'reshape' but I can't seem to work out the correct code to represent topics on the x-axis, the scale 0-1 on the y-axis, and each var (before_event, after_event, current) as three individual lines.

Any help would be really appreciated!

raindance18
  • 11
  • 1
  • 1
  • Learn to search. Use `[r] multiple line plot` and sort by votes. The duplicate was a top answer. – IRTFM Nov 25 '16 at 04:40

2 Answers2

2

We can use matplot from base R

matplot(df1[,1], df1[-1], type = 'l', xlab = "topics", ylab = "event", col = 2:4, pch = 1)
legend("topright", legend = names(df1)[-1], pch = 1, col=2:4)
akrun
  • 874,273
  • 37
  • 540
  • 662
1

we can use ggplot and geom_line

library(ggplot2)

topics <- seq(1,15,1)
before_event <- runif(15, min=0.042, max=0.070)
after_event <- runif(15, min=0.040, max=0.065)
current <- runif(15, min=0.041, max=0.066)

df <- data.frame(topics,before_event,after_event,current) #create data frame from the above vectors

df.m <- melt(df, id.vars="topics") # melt the dataframe using topics as id

# plot the lines using ggplot and geom_line
ggplot(data = df.m,
       aes(x = topics, y = value, group = variable, color = variable)) +
geom_line(size = 2)
Hardik Gupta
  • 4,700
  • 9
  • 41
  • 83