我是 R 包EnvStats的创建者。
有一个我经常使用的函数叫做stripChart
. 我刚刚开始学习ggplot2
,过去几天一直在研究 Hadley 的书、Winston 的书、StackOverflow 和其他资源,试图创建一个geom
近似于实际的东西stripChart
。我无法弄清楚如何在 中geom
计算汇总统计数据和测试结果,然后将它们放置在 x 轴刻度线下方以及绘图顶部(绘图区域外)。这是一个使用内置数据集的简单示例mtcars
:
library(EnvStats)
stripChart(mpg ~ cyl, data = mtcars, col = 1:3,
xlab = "Number of Cylinders", ylab = "Miles per Gallon", p.value = TRUE)
这是一个 geom 的早期草稿,试图重现 stripChart 的大部分功能:
geom_stripchart <-
function(..., x.nudge = 0.3,
jitter.params = list(width = 0.3, height = 0),
mean.params = list(size = 2, position = position_nudge(x = x.nudge)),
errorbar.params = list(size = 1, width = 0.1,
position = position_nudge(x = x.nudge)),
n.text = TRUE, mean.sd.text = TRUE, p.value = FALSE) {
params <- list(...)
jitter.params <- modifyList(params, jitter.params)
mean.params <- modifyList(params, mean.params)
errorbar.params <- modifyList(params, errorbar.params)
jitter <- do.call("geom_jitter", jitter.params)
mean <- do.call("stat_summary", modifyList(
list(fun.y = "mean", geom = "point"),
mean.params)
)
errorbar <- do.call("stat_summary", modifyList(
list(fun.data = "mean_cl_normal", geom = "errorbar"),
errorbar.params)
)
stripchart.list <- list(
jitter,
theme(legend.position = "none"),
mean,
errorbar
)
if(n.text || mean.sd.text) {
# Compute summary statistics (sample size, mean, SD) here?
if(n.text) {
# Add information to stripchart.list to
# compute sample size per group and add text below x-axis
}
if(mean.sd.text) {
# Add information to stripchart.list to
# compute mean and SD and add text above top of plotting region
}
}
if(p.value) {
# Add information to stripchart.list to
# compute p-value (and 95% CI for difference if only 2 groups)
# and add text above top of plotting region
}
stripchart.list
}
library(ggplot2)
dev.new()
p <- ggplot(mtcars, aes(x = factor(cyl), y = mpg, color = factor(cyl)))
p + geom_stripchart() +
xlab("Number of Cylinders") +
ylab("Miles per Gallon")
您可以看到情节几乎相同。我遇到的问题是弄清楚如何在每组下方添加样本量,并在顶部添加均值和标准差,以及 ANOVA 测试的结果(此时忽略不等方差的问题) . 我知道计算汇总统计数据然后将它们绘制为绘图区域内的点或文本很简单,但我不想这样做。
我已经找到了显示如何将文本放置在绘图之外的示例(例如,使用annotation_custom()
):
如何在 ggplot2 的 x 轴下方添加注释?
问题是示例显示了如何在用户预先定义注释的情况下执行此操作。我的问题是geom_stripchart
,我必须根据调用中定义的数据计算汇总统计数据和测试结果ggplot()
,然后将这些结果传递给annotation_custom()
. 我不知道如何获取调用中定义的 x 和 y 变量ggplot()
。