如何使用data.frame文件在ggplot中绘制线图?

时间:2016-04-17 13:03:37

标签: r ggplot2 dataframe line-plot

感谢您的阅读。我发现我无法从现有数据中绘制线图,如下所示:

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 个答案:

答案 0 :(得分:1)

首先,您必须修改data.frame的结构:Protein1&amp; Protein2应该是数字而不是因素。

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

如果你只想绘制&#34; Protein1&#34;,你不需要先使用融化。

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

group = 1允许使用geom_line()source

连接点

现在,如果你想看到Protein1&amp; 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