如何在R中制作点图网格

时间:2016-09-16 07:54:53

标签: r plot grid stata

我有新生儿兄弟姐妹体重和性别的数据样本,并希望将它们绘制在R中常见的2x2点图上,如下图所示: 2x2 plot of birthweight of first compared to second child

stata代码就是这个

count($times):  97
min:    2.6941299438477E-5
max:   10.68115234375E-5
avg:    3.3095939872191E-5
median: 3.0517578125E-5
sum:  321.03061676025E-5

the same results with notation without E-5
count($times):  97
min:    0.000026941299438477
max:    0.0001068115234375
avg:    0.000033095939872191
median: 0.000030517578125
sum:    0.0032103061676025

R中数据的结构如下:

egen sex1sex2=group(sex1st sex2nd),label
scatter weight2nd weight1st,by(sex1sex2) aspect(1) scheme(s1mono)

只需要考虑1:4。 在性爱中,1 =男孩,2 =女孩。在原始.dta文件中,它们被标记。

我找到了这个帖子,我认为这是要走的路,但我不知道如何绕过它:Dot Plots with multiple categories - R

非常感谢您的帮助。

1 个答案:

答案 0 :(得分:1)

在您分享的主题中,答案建议使用ggplot2执行绘图。它是一个外部包,对于在R中生成(主观上)更具视觉吸引力的绘图非常有用。它对于 faceting 特别有用,这正是你想要做的。

首先,您需要安装并加载库。

install.packages('ggplot2')
library('ggplot2')

我已经创建了一些虚拟数据来说明这个过程:

x <- data.frame("sex1" = sample(1:2, 1000, replace = T),
                "sex2" = sample(1:2, 1000, replace = T),
                "weight1" = round(rnorm(1000, mean = 3000, sd = 100)),
                "weight2" = round(rnorm(1000, mean = 3000, sd = 100)))

现在我们开始使用ggplot2开始绘图。我将通过首先绘制没有方面的所有内容来展示 faceting 的样子。基本上,这绘制了权重1(x轴)乘以权重2(y轴)的散点图:

p1 <- ggplot(x, aes(x = weight1, y = weight2)) + geom_point()
print(p1)

enter image description here

右。现在,让我们添加您想要的两个方面,即sex1sex2

faceted <- p1 + facet_wrap(~sex1 + sex2, ncol = 2, nrow = 2)
print(faceted)

enter image description here

虽然这直接解决了您的问题,但我建议您阅读有关语法和应用程序的更多信息,以了解ggplot的功能。