使用R中绘制的标准错误创建条形图

詹姆斯·怀特

我正在尝试找到在R中创建显示标准错误的条形图的最佳方法。我看过其他文章,但无法弄清楚用于我自己的数据的代码(以前没有使用过ggplot,这似乎是最常用的方式,并且barplot不与数据帧配合使用)。我在两种情况下都需要使用它,为此我创建了两个示例数据框:

绘制df1,使x轴具有ac位置,y轴显示V1的平均值,并突出显示标准误差,类似于本示例中的灰色。在这里,植物生物量应为平均V1值,处理方法应为我的每个站点。

以相同的方式绘制df2,但是之前和之后以与相似的方式彼此相邻,因此在我的示例中,预测试和后测试等同于之前和之后。

x <- factor(LETTERS[1:3])
site <- rep(x, each = 8)
values <- as.data.frame(matrix(sample(0:10, 3*8, replace=TRUE), ncol=1))
df1 <- cbind(site,values)
z <- factor(c("Before","After"))
when <- rep(z, each = 4)
df2 <- data.frame(when,df1)

为经验丰富的R用户(尤其是使用ggplot的用户)提供的简单性道歉,但是我无法将在其他地方找到的代码片段应用于数据。我什至无法获得足够的代码来生成图表的起点,所以我希望我的描述足够了。先感谢您。

达瓦尔·卡皮尔(Dhawal Kapil)

我使用了它,group_bysummarise_each function为此和包中的std.error函数plotrix

library(plotrix) # for std error function
library(dplyr) # for group_by and summarise_each function
library(ggplot2) # for creating ggplot

对于df1图

# Group data by when and site
grouped_df1<-group_by(df1,site)

#summarise grouped data and calculate mean and standard error using function mean and std.error(from plotrix)
summarised_df1<-summarise_each(grouped_df1,funs(mean=mean,std_error=std.error))


# Define the top and bottom of the errorbars
limits <- aes(ymax = mean + std_error, ymin=mean-std_error)

#Begin your ggplot
#Here we are plotting site vs mean and filling by another factor variable when
g<-ggplot(summarised_df1,aes(site,mean))

#Creating bar to show the factor variable position_dodge 
#ensures side by side creation of factor bars
g<-g+geom_bar(stat = "identity",position = position_dodge())

#creation of error bar
g<-g+geom_errorbar(limits,width=0.25,position = position_dodge(width = 0.9))
#print graph
g

在此处输入图片说明

对于df2图

# Group data by when and site
grouped_df2<-group_by(df2,when,site)

#summarise grouped data and calculate mean and standard error using function mean and std.error
summarised_df2<-summarise_each(grouped_df2,funs(mean=mean,std_error=std.error))

# Define the top and bottom of the errorbars
limits <- aes(ymax = mean + std_error, ymin=mean-std_error)

#Begin your ggplot
#Here we are plotting site vs mean and filling by another factor variable when
g<-ggplot(summarised_df2,aes(site,mean,fill=when))

#Creating bar to show the factor variable position_dodge 
#ensures side by side creation of factor bars
g<-g+geom_bar(stat = "identity",position = position_dodge())

#creation of error bar
g<-g+geom_errorbar(limits,width=0.25,position = position_dodge(width = 0.9))
#print graph
g

在此处输入图片说明

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章