0

Thank you for reading. I find that I am unable to draw line plot from my existing data as below:

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

What I need is to draw a graph as below:

enter image description here

I have tried the following codes but the results are not ok;

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

Also:

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

So many thanks for your care.

joran
  • 169,992
  • 32
  • 429
  • 468
Sadegh
  • 788
  • 5
  • 15

1 Answers1

1

First, you have to modify the structure of your data.frame : Protein1 & Protein2 should be numeric and not factors.

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

If you only want to plot "Protein1", you do not need to use melt first.

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

group = 1 permits connecting points with geom_line() : source


Now, if you want to see Protein1 & Protein2 on the same plot, you can use 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

Community
  • 1
  • 1
bVa
  • 3,839
  • 1
  • 13
  • 22
  • Thank you very much. Could you please help me to add the legends on the lines within the plot? – Sadegh Apr 18 '16 at 08:13
  • 1
    If you only want to move the legend (bottom, right), use : `+ theme(legend.justification=c(1,0), legend.position=c(1,0))` If you want to only write the labels : `+ geom_text(data = a1[a1$ID == " day3",], aes(label = variable), vjust = -1, hjust = 0)`. Be careful, I saw that the levels of ID are " day1", with a blank character. – bVa Apr 18 '16 at 08:36
  • perfect. Thank you. Just one more point. Do you know how is it possible to add a label per line instead of a label per point? one "Protein1" word for red line and one "Protein2" word for blue one. – Sadegh Apr 18 '16 at 10:19
  • 1
    You have to explicit the subset of the date, with only one point (for example " day3", or " day1", ...) for each "protein": `geom_text(data = a1[a1$ID == " day3",], aes(label = variable), vjust = -1, hjust = 0)` – bVa Apr 18 '16 at 12:37