【问题标题】:How to make a grid of dot plots in R如何在R中制作点图网格
【发布时间】:2016-09-16 07:54:53
【问题描述】:

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

stata代码是这个

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

R中数据的结构是这样的:

> str(siblings)
'data.frame':   1000 obs. of  5 variables:
 $ sex1st   : int  1 1 1 2 1 1 2 1 2 2 ...
 $ sex2nd   : int  1 2 1 2 2 2 1 2 2 1 ...
 $ weight1st: int  3740 3060 3650 3688 3740 3550 3850 3680 2390 3600 ...
 $ weight2nd: int  3740 3620 3700 3726 3000 3700 4020 4310 2250 3250 ...
 $ difw     : int  0 560 50 38 -740 150 170 630 -140 -350 ...

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

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

非常感谢您的帮助。

【问题讨论】:

  • 不只是 Stata 的名字:我想大多数人都会称这些散点图。
  • 嗨尼克。我认为你完全正确。散点图是更正确的术语。我目前正在学习生物统计学课程,课程材料是通过 Stata 代码提供的,但我一直致力于使用 R,所以我有时会遇到一些小问题。

标签: r plot grid stata


【解决方案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 的样子。基本上,这绘制了 weight1(x 轴)按 weight2(y 轴)的散点图:

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

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

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

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

【讨论】:

  • 完美!那真的做到了。非常感谢。我对 R 还是很陌生,所以我肯定会回去学习!不过非常感谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-05-07
  • 2021-02-15
  • 2022-11-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多