2012-09-19 43 views
0

這個問題的主題很簡單,但讓我發瘋: 1.如何使用melt() 2.如何處理單行圖像中的多行?ggplot2與時間系列和多樣條線繪製

這裏是我的原始數據:

a 4.17125 41.33875 29.674375 8.551875 5.5 
b 4.101875 29.49875 50.191875 13.780625 4.90375 
c 3.1575 29.621875 78.411875 25.174375 7.8012 

Q1: 我從這篇文章Plotting two variables as lines using ggplot2 on the same graph學會求知,如何繪製多線多變量,就像這樣: enter image description here

以下代碼可以得到上面的圖。但是,x軸確實是時間序列。

df <- read.delim("~/Desktop/df.b", header=F) 
colnames(df)<-c("sample",0,15,30,60,120) 
df2<-melt(df,id="sample") 
ggplot(data = df2, aes(x=variable, y= value, group = sample, colour=sample)) + geom_line() + geom_point() 

我希望它可以治療0 15 30 60 120實數來顯示時間系列,而不是name_characteristics。即使嘗試過,我失敗了。

row.names(df)<-df$sample 
df<-df[,-1] 
df<-as.matrix(df) 
df2 <- data.frame(sample = factor(rep(row.names(df),each=5)), Time = factor(rep(c(0,15,30,60,120),3)),Values = c(df[1,],df[2,],df[3,])) 
ggplot(data = df2, aes(x=Time, y= Values, group = sample, colour=sample)) 
     + geom_line() 
     + geom_point() 

Loooooooooking轉發給你的幫助。

Q2: 我明白了,下面的腳本可以添加樣條()函數爲單一條線,那我想爲所有三行在單一一個圖像應用花鍵()?

n <-10 
d <- data.frame(x =1:n, y = rnorm(n)) 
ggplot(d,aes(x,y))+ geom_point()+geom_line(data=data.frame(spline(d, n=n*10))) 

回答

3

variable列是一個因素(可以通過調用str(df2)驗證)。只需將其轉換回數字:

df2$variable <- as.numeric(as.character(df2$variable)) 

對於您的其他問題,你可能要堅持使用geom_smoothstat_smooth,這樣的事情:

p <- ggplot(data = df2, aes(x=variable, y= value, group = sample, colour=sample)) + 
     geom_line() + 
     geom_point() 

library(splines) 
p + geom_smooth(aes(group = sample),method = "lm",formula = y~bs(x),se = FALSE) 

,給了我這樣的:

enter image description here

+0

非常感謝您的幫助!我嘗試過'as.numeric(df2 $ Time)'在我的情況下將它們轉換爲數字,但它返回給我''1 2 3 4 5 1 2 3 4 5 1 2 3 4 5''這真的讓我發瘋。再次感謝。 – Puriney

+0

@Puriney請注意,這不是我如何在我的答案中進行轉換。因素_look_喜歡角色載體,但它們不是**!它們是整數代碼和一組與代碼一起使用的標籤。因此,'as.numeric'只會返回整數代碼。這就是爲什麼我首先轉換爲角色。一個更神祕的方法是'as.numeric(levels(df2 $ Time)[df2 $ Time])''。 – joran