在 ggplot2 条形图上将误差线设置为标准差

问题描述 投票:0回答:2

我有一个使用 ggplot2 的二因素条形图,其中我使用mean_se 添加带有标准误差的误差条。我想使用标准差而不是标准误差。

library(tidyverse)

#load diamonds dataset
diamonds <- diamonds

#two-factor dynamite plot
plt <- ggplot(diamonds, aes(cut, price, fill = color)) +
geom_bar(stat = "summary", fun.y = "mean", position = position_dodge(width = 
0. 9)) +
geom_errorbar(stat = "summary", fun.data = "mean_se", position = 
position_dodge(width = 0.9)) +
ylab("mean price") +
ggtitle("Two-Factor Dynamite plot")

plt

有没有一种方法可以类似于使用mean_se,但生成代表一个标准差的误差线? mean_sdl 似乎没有这样做。谢谢你。

r ggplot2
2个回答
3
投票

mean_sdl
采用参数
mult
指定标准差的数量 - 默认情况下为
mult = 2
。所以你需要通过
mult = 1
:

plt <- ggplot(diamonds, aes(cut, price, fill = color)) +
    geom_bar(stat = "summary", fun.y = "mean", 
             position = position_dodge(width = 0.9)) +
    geom_errorbar(stat = "summary", fun.data = "mean_sdl", 
                  fun.args = list(mult = 1),
                  position =  position_dodge(width = 0.9)) +
    ylab("mean price") +
    ggtitle("Two-Factor Dynamite plot")

plt

0
投票

一个简单的解决方案是定义一个与平均值相关的区间函数。这是通过包

superb

完成的
library(superb)
library(ggplot2)

#load diamonds dataset
diamonds <- diamonds

# attach an interval function to the mean
SD.mean <- function(x){ sd(x) } 

superb(price ~ cut + color, diamonds,
  errorbar = "SD"
) + 
ylab("mean price") +
ggtitle("Two-Factor Dynamite plot")

我们得到:

result mean with SD as error bar

© www.soinside.com 2019 - 2024. All rights reserved.