2016-11-25 77 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)