2016-11-25 79 views
0

我似乎无法弄清楚如何为多线图创建图形。R使用数据帧的多线图

这是我的数据框:

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 

在数据帧中的变量都是数字载体,例如:

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

我知道我应该使用'ggplot2'和'reshape',但我似乎无法找出正确的代码来表示主题在x轴上为,在y轴上为0-1,并且每个var(before_event,after_event,当前)作为三条独立线。

任何帮助将非常感谢!

+0

学会搜索。使用'[r]多线图'并按票数排序。重复是最好的答案。 –

回答

1

我们可以使用matplotbase 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) 
1

我们可以使用ggplot和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)