我如何在R中使用ggplot2绘制来自不同数据帧的两个序列彼此相对,而不建立新的数据帧? [英] How can I plot two series from different data frames against each other with ggplot2 in R without building a new data frame?

查看:43
本文介绍了我如何在R中使用ggplot2绘制来自不同数据帧的两个序列彼此相对,而不建立新的数据帧?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有两个数据帧

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)

到目前为止,我对ggplot2的了解还是可以的

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:

推荐答案

以下任何一行(均取自注释)应该起作用:

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

我更喜欢最后一行(摘自已删除的评论).如问题评论中所述, ggplot()仍将创建一个 data.frame .这些解决方案的作用是允许用户略微忽略数据管理的这一方面(诚然,某些用户会觉得可恶).

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

这篇关于我如何在R中使用ggplot2绘制来自不同数据帧的两个序列彼此相对,而不建立新的数据帧?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆