Heisenberg
Heisenberg

Reputation: 8816

x and y variables are from different data frame (ggplot2)

I'm learning ggplot2 so please excuse my novice understanding.

Is there a way to do a simple scatter plot when x and y are from two different data frames? For example:

p <- ggplot(data=df1, aes(x=x.in.df1))
p + geom_point(data=df2, aes(y=y.in.df2))

Since x.in.df1 does not exist in df2, when geom_point tries to look for x in df2, it fails.

EDIT: The reason why I hesitate to cbind is because I have many data frames with the same variables. For example, df2000 contains variables GDP, GDP growth for all countries in year 2000. df2001 is the same for year 2001.

Upvotes: 2

Views: 4843

Answers (1)

NotAPhysicist
NotAPhysicist

Reputation: 57

Credit goes to @Roland; I'm just posting his comment as an answer here for future readers like myself who encounter the same/similar problems.

ggplot(data = data.frame(x = df1$x, y = df2$y), aes(x = x, y = y))

Thanks for the elegant solution @Roland.

Upvotes: 3

Related Questions