本教程介紹如何使用R軟件和ggplot2包創建帶有誤差棒的圖形。 可以使用以下函數創建不同類型的錯誤欄:
geom_errorbar() geom_linerange() geom_pointrange() geom_crossbar() geom_errorbarh()
準備數據 使用ToothGrowth數據。 它描述了維生素C對豚鼠牙齒生長的影響。 使用三種劑量水平的維生素C(0.5mg,1mg和2 mg)和兩種遞送方法[橙汁(OJ)或抗壞血酸(VC)]中的每一種:
> library(ggplot2) > df <- ToothGrowth > df$dose <- as.factor(df$dose) > head(df) len supp dose 1 4.2 VC 0.5 2 11.5 VC 0.5 3 7.3 VC 0.5 4 5.8 VC 0.5 5 6.4 VC 0.5 6 10.0 VC 0.5
len:齒長 dose:劑量單位爲mg(0.5,1,2) supp:補充類型(VC或OJ) 在下面的示例中,我們將繪製每組中Tooth長度的平均值。 標準差用於繪製圖形上的誤差線。首先,使用下面的輔助函數將用於計算每組感興趣變量的均值和標準差。
#+++++++++++++++++++++++++ # Function to calculate the mean and the standard deviation # for each group #+++++++++++++++++++++++++ # data : a data frame # varname : the name of a column containing the variable #to be summariezed # groupnames : vector of column names to be used as # grouping variables data_summary <- function(data, varname, groupnames){ require(plyr) summary_func <- function(x, col){ c(mean = mean(x[[col]], na.rm=TRUE), sd = sd(x[[col]], na.rm=TRUE)) } data_sum<-ddply(data, groupnames, .fun=summary_func, varname) data_sum <- rename(data_sum, c("mean" = varname)) return(data_sum) } df2 <- data_summary(ToothGrowth, varname="len", groupnames=c("supp", "dose")) # Convert dose to a factor variable df2$dose=as.factor(df2$dose) head(df2)
- 向條形圖添加誤差線
函數geom_errorbar()可用於生成誤差棒:
library(ggplot2) # Default bar plot p<- ggplot(df2, aes(x=dose, y=len, fill=supp)) + geom_bar(stat="identity", color="black", position=position_dodge()) + geom_errorbar(aes(ymin=len-sd, ymax=len+sd), width=.2, position=position_dodge(.9)) print(p) # Finished bar plot p+labs(title="Tooth length per dose", x="Dose (mg)", y = "Length")+ theme_classic() + scale_fill_manual(values=c('#999999','#E69F00'))
- 使用線圖繪製誤差棒
# Default line plot p<- ggplot(df2, aes(x=dose, y=len, group=supp, color=supp)) + geom_line() + geom_point()+ geom_errorbar(aes(ymin=len-sd, ymax=len+sd), width=.2, position=position_dodge(0.05)) print(p) # Finished line plot p+labs(title="Tooth length per dose", x="Dose (mg)", y = "Length")+ theme_classic() + scale_color_manual(values=c('#999999','#E69F00'))
- 使用點圖繪製誤差棒
p <- ggplot(df, aes(x=dose, y=len)) + geom_dotplot(binaxis='y', stackdir='center') # use geom_crossbar() p + stat_summary(fun.data="mean_sdl", fun.args = list(mult=1), geom="crossbar", width=0.5) # Use geom_errorbar() p + stat_summary(fun.data=mean_sdl, fun.args = list(mult=1), geom="errorbar", color="red", width=0.2) + stat_summary(fun.y=mean, geom="point", color="red") # Use geom_pointrange() p + stat_summary(fun.data=mean_sdl, fun.args = list(mult=1), geom="pointrange", color="red")
使用函數geom_dotplot()和stat_summary():
平均值+/- SD可以添加爲誤差條或點範圍: