问题描述
我将一个变量的值绘制为一维线上的点(在一个空的二维空间中)。我想在该图中说明围绕平均值的变化(即标准偏差)。 SD 大约为 2。因此,我正在考虑以平均值为中心的那种大小的两侧箭头。我如何在 ggplot2
中执行此操作? (示例中的箭头是素色的,在 ggplot 中可能会有所不同。)
library(tidyverse)
data(sleep)
ggplot(aes(x=extra,y=c(0)),data=sleep) +
geom_point(size=3) +
labs(title="distribution of a variable around the mean") +
geom_vline(xintercept=mean(sleep$extra),size=1.5,color="red")
sd(sleep$extra)
2.01792
编辑:我发现这个来源 http://stla.overblog.com/schematizing-the-variance-as-a-moment-of-inertia 使用带箭头的椭圆,我也觉得它非常引人注目。
解决方法
要回答有关显示标准偏差的直接问题,使用 errorbar(垂直误差线)或 errorbarh(水平误差线)几何图形可能是最简单的。以下是如何在您的示例中展示这一点:
ggplot(aes(x=extra,y=c(0)),data=sleep) +
geom_errorbarh(xmin=mean(sleep$extra) - sd(sleep$extra),xmax=mean(sleep$extra) + sd(sleep$extra)) +
geom_point(size=3) +
labs(title="Distribution of a variable around the mean") +
geom_vline(xintercept=mean(sleep$extra),size=1.5,color="red")
通常,通过箱线图将一维分布可视化更为常见。以下是您可以如何在此处应用的示例:
ggplot(aes(x=extra,data=sleep) +
geom_boxplot() +
geom_point(size=3) +
labs(title="Distribution of a variable around the mean") +
geom_vline(xintercept=mean(sleep$extra),color="red")
您会注意到用于箱线图的统计数据通常是不同的。它显示的是中位数和分位数,而不是平均值和标准差。
,我认为您应该使用 geom_errorbar
包中的 ggplot2
之类的东西
df <- data.frame(means = rnorm(20,5,2),sds = rnorm(20),feats = c(paste0("Feature ",letters[1:10])),group = rep(c("group 1","group 2"),each = 2))
library(ggplot2)
ggplot(df,aes(x = feats,color = group)) +
geom_errorbar(aes(ymax = means + sds,ymin = means - sds),position = "dodge")