How can I plot two series from different data frames against each other with ggplot2 in R without building a new data frame?

◇◆丶佛笑我妖孽 提交于 2021-02-07 08:26:57

问题


Suppose that I have two data frames

df1 = data.frame(x=1:10)
df2 = data.frame(x=11:20)

and I want a scatter plot with these two series defining the coordinates. It would be simple to do

plot(df1$x,df2$x)

From what I can tell so far about ggplot2, I could also do

df = data.frame(x1 = df1$x, x2 = df2$x)
ggplot(data = df, aes(x=x1, y=x2)) + geom_point()
rm(df)

but that would be slower (for me) than not creating a new data frame, is hard to read, and could lead to increased mistakes (deleting the wrong data frame, writing over a needed data frame, forgetting to remove the excess clutter, etc.). Do I really need to create a separate data frame just to house the data that are already there? Why does the first line of the following work even though it only lists one of the data frames under "data" while the second line does not?

ggplot(data = df1, aes(x=df1$x, y=df2$x)) + geom_point()
ggplot(            aes(x=df1$x, y=df2$x)) + geom_point()

Here is an example image of basically what I want:


回答1:


Any line of the following (all taken from comments) should work:

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

ggplot() + geom_point(aes(x=df1$x, y=df2$x))

ggplot(data=NULL, aes(x=df1$x, y=df2$x)) + geom_point()

ggplot(data=df1, aes(x=x)) + geom_point(aes(y=df2$x))

I prefer the last line (taken from a comment that was deleted). As mentioned in comments on the question, ggplot() will create a data.frame anyway. What these solutions do is permit the user to ignore this aspect of data management somewhat (admittedly in ways that some users would find abhorrent).




回答2:


This was going to be a comment, but I'm not reputable enough yet.

You could also try qplot(x = df1$x, y = df2$x). Note that from ?qplot that qplot will create a data frame for you from the inputs provided, if the data argument is left unset.



来源:https://stackoverflow.com/questions/32321396/how-can-i-plot-two-series-from-different-data-frames-against-each-other-with-ggp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!