Rechlay
Rechlay

Reputation: 1517

How to add line using other data to ggplot?

I would like to add a line to my data:

Part of my data:

dput(d[1:20,])
structure(list(MW = c(10.8, 10.9, 11, 11.7, 12.8, 16.6, 16.9, 
17.1, 17.4, 17.6, 18.5, 19.1, 19.2, 19.7, 19.9, 20.1, 22.4, 22.7, 
23.4, 24), Fold = c(21.6, 21.8, 22, 23.4, 25.6, 33.2, 33.8, 34.2, 
34.8, 35.2, 37, 38.2, 38.4, 39.4, 39.8, 40.2, 44.8, 45.4, 46.8, 
48), Column = c(33.95, 33.95, 33.95, 33.95, 33.95, 33.95, 33.95, 
33.95, 33.95, 33.95, 33.95, 33.95, 33.95, 33.95, 33.95, 33.95, 
33.95, 33.95, 33.95, 33.95), Bool = c(1, 1, 1, 1, 1, 1, 1, 1, 
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1)), .Names = c("MW", "Fold", 
"Column", "Bool"), row.names = c(NA, 20L), class = "data.frame")

data for line:

> dput(bb[1:20,])
structure(c(1.95, 3.2, 3.7, 4.05, 4.5, 4.7, 4.75, 5.05, 5.2, 
5.2, 5.2, 5.25, 5.3, 5.35, 5.35, 5.4, 5.4, 5.45, 5.5, 5.5, 10, 
33.95, 58.66, 84.42, 110.21, 134.16, 164.69, 199.1, 234.35, 257.19, 
361.84, 432.74, 506.34, 581.46, 651.71, 732.59, 817.56, 896.24, 
971.77, 1038.91), .Dim = c(20L, 2L), .Dimnames = list(NULL, c("b", 
"a")))

And as the last the code which I use to create this plot:

first_dot <- ggplot(d, aes(x=MW, y=Column)) +
  geom_point() +
  scale_x_continuous(limits=c(0, 650), breaks=c(0, 200, 400, 650)) +
  scale_y_continuous(limits=c(0, 1200), breaks=c(0, 400, 800, 1200))


first_dot + geom_line(bb, aes(x=b, y=a))

I get this error all the time when I try to run it:

Error: ggplot2 doesn't know how to deal with data of class uneval

Do you have any idea what I do wrong ?

That's how the data look like without line:

No line

And how it should look like after adding like (approximately):

with line

Upvotes: 1

Views: 12916

Answers (2)

PavoDive
PavoDive

Reputation: 6496

Just in case somebody lands here looking for an answer to the [underlying] question of "how to plot a line from a different data frame on top of an existing plot":

The key point here is to use the data= in the call to geom_line. Assuming that the data= is not required has happened to some of us, and often is the reason it doesn't work. Correct code would be, as @Roland put in the comments to the question:

ggplot(d, aes(x=MW, y=Column)) +
     geom_point() +
     scale_x_continuous(limits=c(0, 650), breaks=c(0, 200, 400, 650)) +
     scale_y_continuous(limits=c(0, 1200), breaks=c(0, 400, 800, 1200))+
     geom_line(data=as.data.frame(bb),aes(x=b,y=a))

Upvotes: 7

Nikos
Nikos

Reputation: 3297

Unfortunately your bb variable is a numberical table so this cannot be plotted by ggplot. Could you try the following:

first_dot + geom_line(data=data.frame(bb), aes(x=b, y=a))

Please note that you convert the bb variable to a data.frame.

Upvotes: 3

Related Questions