2016-04-17 71 views
0

謝謝您的閱讀。我發現我無法從我現有的數據中得出線圖如下:如何使用data.frame文件在ggplot中繪製線條圖?

a=structure(list(ID = structure(1:3, .Names = c("V2", "V3", "V4" 
), .Label = c(" day1", " day2", " day3"), class = "factor"), 
    Protein1 = structure(c(3L, 1L, 2L), .Names = c("V2", 
    "V3", "V4"), .Label = c("-0.651129553", "-1.613977035", "-1.915631511" 
    ), class = "factor"), Protein2 = structure(c(3L, 
    1L, 2L), .Names = c("V2", "V3", "V4"), .Label = c("-1.438858662", 
    "-2.16361761", "-2.427593862"), class = "factor")), .Names = c("ID", 
"Protein1", "Protein2"), row.names = c("V2", 
"V3", "V4"), class = "data.frame") 

我需要的是繪製如下圖:

enter image description here

我曾嘗試以下代碼但結果不好;

qplot(ID, Protein1, data=a, colour=ID, geom="line") 

另外:

a1<-melt(a, id.vars="ID") 
ggplot(a1,aes(ID,value))+ geom_line()+geom_point() 

所以非常感謝您的關心。

回答

1

首先,您必須修改您的data.frame的結構:Protein1 & Protein2應該是數字而不是因子。

a$Protein1 = as.numeric(as.character(a$Protein1)) 
a$Protein2 = as.numeric(as.character(a$Protein2)) 

如果您只想繪製「Protein1」,則不需要先使用融化。

ggplot(a, aes(x = ID, y = Protein1)) + geom_point() + geom_line(aes(group = 1)) + ylim(-3,3) 

group = 1許可證與geom_line()連接點:source


現在,如果你想看到Protein1 & Protein2在同一個情節,你可以使用melt

a1<-melt(a, id.vars="ID") 
ggplot(a1, aes(x = ID, y = value, group = variable, color = variable)) + geom_point() + geom_line() + ylim(-3,3) 

enter image description here

+0

非常感謝。你能幫我把這些圖例添加到劇情的內容中嗎? – Sadegh

+1

如果您只想移動圖例(底部,右側),請使用: '+ theme(legend.justification = c(1,0),legend.position = c(1,0))' 如果您想要只寫標籤: '+ geom_text(data = a1 [a1 $ ID ==「day3」,],aes(label = variable),vjust = -1,hjust = 0)'。 要小心,我看到ID的級別是「day1」,空白字符。 – bVa

+0

完美。謝謝。還有一點。你知道怎麼可能每行添加一個標籤而不是每個標籤的標籤?一個用於紅線的「Protein1」字和一個用於藍線的「Protein2」字。 – Sadegh

相關問題