在 R 中创建误差线 (ggplot2)

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

我一直致力于创建带有误差线的条形图来描述我拥有的数据集的组差异。但错误栏显得很奇怪,因为它们出现在栏的上方和栏的中间。

我的代码:

ggplot(MRS_Hippo_NAA_Cre_Data_copy, aes(Type, Hippo_6_9NAACre, fill=Type)) + 
geom_bar(stat="summary", fun.y="mean", colour="black", size=.3) + 
geom_errorbar(aes(ymin=meanNAA-NAAse, ymax=meanNAA+NAAse), width=.2, 
position=position_dodge(.9)) + labs(x="Group", y="Right Posterior NAA/Cre") + 
scale_fill_manual(values=c("#0072B2", "#D55E00"), name="Group") + theme(text = 
element_text(size=18))`

这产生了这个图表:

plot

我使用以下函数计算了标准误差:

std <- function(x) sd(x)/sqrt(length(x)) 

x=Hippo_6_9NAACre

不知道为什么图表会产生奇怪的误差线。任何人都可以提供帮助或提供见解吗?

r ggplot2
2个回答
1
投票

我最近也遇到了类似的问题。 要解决这个问题,首先您可能需要删除图层

geom_errorbar(aes(ymin=meanNAA-NAAse, 
ymax=meanNAA+NAAse), width=.2, position=position_dodge(.9))

而是再次使用具有

statsummary
功能的图层。这将生成按组分开的误差线。 由于您希望条形指示标准错误,因此您必须创建一个返回所需值的适当函数,以便可以在
statsummary
中使用。 下面是一个使用
iris
数据集的工作示例。

library(ggplot2)

## create a function for standard error that can be used with stat_summary
# I created the function inspecting the results returned by 'mean_cl_normal' that is the         
# function used in some examples of stat_summary (see ?stat_summary).

mean_se = function(x){
 se = function(x){sd(x)/sqrt(length(x))}
data.frame(y=mean(x), ymin=mean(x)+se(x), ymax=mean(x)-se(x))
}

## create the plot
p = ggplot(iris, aes(x = Species, y = Sepal.Length), stat="identity") +
stat_summary(fun.y = mean, geom = "col", fill = "White", colour = "Black", width=0.5) + 
stat_summary(fun.data = mean_se, geom = "errorbar", width=0.2, size=1)

# print the plot
print(p)

0
投票

这正是创建

superb
包的原因:获取汇总统计数据和误差线图。在本例中,基本图是通过

获得的
library(superb)
superb( Sepal.Length ~ Species, iris)

这再简单不过了!

如果您希望显示标准误差而不是默认的 95% 置信区间,请添加参数

errorbar = "SE"
。此外,您还可以使用参数
plotStyle="line"
绘制线图,而不是条形图(默认)。在这里,使用
plotStyle="pointjitter"
抖动的点可能会提供更多信息,或者使用
plotStyle="raincloud"
绘制雨云图!

基于精湛的绘图是

ggplot2
,因此它们接受您可能想要的任何图形指令。这是一个更吸引人的雨云图:

library(superb)
superb( Sepal.Length ~ Species, iris,
  errorbar= "SE",
  plotStyle = "raincloud",
  jitterParams = list(color="purple", width=0.05),
  violinParams = list(fill="green", alpha = 0.2)
) +
theme_bw() + 
ylab("Sepal length")

sepal length as a function of species with error bars

费舍尔希望他有 R!

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