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

How to draw a line plot in ggplot using a data.frame file?

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

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")

我需要绘制如下图:

我已经尝试了以下代码,但结果不正确;

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

还有:

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

非常感谢您的关心。

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

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

如果只想绘图"Protein1",则不需要先使用melt。

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)