如何在 R 中的一维图中可视化标准偏差?

How to visualize standard deviation in a one-dimensional plot in R?

我将一个变量的值绘制为一维线上的点(在其他空的二维 space 中)。我想在该图中说明 围绕均值 (即标准差)的变化。 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 使用带箭头的椭圆,我也觉得它非常引人注目。

我认为你应该使用 ggplot2 包中的 geom_errorbar 之类的东西

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

要回答关于显示标准差的直接问题,最简单的方法可能是使用 errorbar(垂直误差线)或 errorbarh(水平误差线)geom。以下是如何在您的示例中显示:

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, y=c(0)), data=sleep) + 
  geom_boxplot() +
  geom_point(size=3) +
  labs(title="Distribution of a variable around the mean") +
  geom_vline(xintercept=mean(sleep$extra), size=1.5, color="red") 

您会注意到用于箱线图的统计数据通常是不同的。它显示的是中位数和分位数,而不是均值和标准差。