Plotting means and error bars (ggplot2)

library(ggplot2)

#############################################
#  summarySE
#############################################

## Summarizes data.
## Gives count, mean, standard deviation, standard error of the mean, and confidence interval (default 95%).
##   data: a data frame.
##   measurevar: the name of a column that contains the variable to be summariezed
##   groupvars: a vector containing names of columns that contain grouping variables
##   na.rm: a boolean that indicates whether to ignore NA‘s
##   conf.interval: the percent range of the confidence interval (default is 95%)
summarySE <- function(data=NULL, measurevar, groupvars=NULL, na.rm=FALSE,
                      conf.interval=.95, .drop=TRUE) {
    library(plyr)

    # New version of length which can handle NA‘s: if na.rm==T, don‘t count them
    length2 <- function (x, na.rm=FALSE) {
        if (na.rm) sum(!is.na(x))
        else       length(x)
    }

    # This does the summary. For each group‘s data frame, return a vector with
    # N, mean, and sd
    datac <- ddply(data, groupvars, .drop=.drop,
      .fun = function(xx, col) {
        c(N    = length2(xx[[col]], na.rm=na.rm),
          mean = mean   (xx[[col]], na.rm=na.rm),
          sd   = sd     (xx[[col]], na.rm=na.rm)
        )
      },
      measurevar
    )

    # Rename the "mean" column
    datac <- rename(datac, c("mean" = measurevar))

    datac$se <- datac$sd / sqrt(datac$N)  # Calculate standard error of the mean

    # Confidence interval multiplier for standard error
    # Calculate t-statistic for confidence interval:
    # e.g., if conf.interval is .95, use .975 (above/below), and use df=N-1
    ciMult <- qt(conf.interval/2 + .5, datac$N-1)
    datac$ci <- datac$se * ciMult

    return(datac)
}

#############################################
# Sample data
#############################################

library(ggplot2)
tg <- ToothGrowth
head(tg)

tgc <- summarySE(tg, measurevar="len", groupvars=c("supp","dose"))
tgc

#############################################
# Line graphs
#############################################

# Standard error of the mean
ggplot(tgc, aes(x=dose, y=len, colour=supp)) +
    geom_errorbar(aes(ymin=len-se, ymax=len+se), width=.1) +
    geom_line() +
    geom_point()

# The errorbars overlapped, so use position_dodge to move them horizontally
pd <- position_dodge(0.1) # move them .05 to the left and right

ggplot(tgc, aes(x=dose, y=len, colour=supp)) +
    geom_errorbar(aes(ymin=len-se, ymax=len+se), width=.1, position=pd) +
    geom_line(position=pd) +
    geom_point(position=pd)

# Use 95% confidence interval instead of SEM
ggplot(tgc, aes(x=dose, y=len, colour=supp)) +
    geom_errorbar(aes(ymin=len-ci, ymax=len+ci), width=.1, position=pd) +
    geom_line(position=pd) +
    geom_point(position=pd)

# Black error bars - notice the mapping of ‘group=supp‘ -- without it, the error
# bars won‘t be dodged!
ggplot(tgc, aes(x=dose, y=len, colour=supp, group=supp)) +
    geom_errorbar(aes(ymin=len-ci, ymax=len+ci), colour="black", width=.1, position=pd) +
    geom_line(position=pd) +
    geom_point(position=pd, size=3)

# A finished graph with error bars representing the standard error of the mean might
# look like this. The points are drawn last so that the white fill goes on top of
# the lines and error bars.

ggplot(tgc, aes(x=dose, y=len, colour=supp, group=supp)) +
    geom_errorbar(aes(ymin=len-se, ymax=len+se), colour="black", width=.1, position=pd) +
    geom_line(position=pd) +
    geom_point(position=pd, size=3, shape=21, fill="white") + # 21 is filled circle
    xlab("Dose (mg)") +
    ylab("Tooth length") +
    scale_colour_hue(name="Supplement type",    # Legend label, use darker colors
                     breaks=c("OJ", "VC"),
                     labels=c("Orange juice", "Ascorbic acid"),
                     l=40) +                    # Use darker colors, lightness=40
    ggtitle("The Effect of Vitamin C on\nTooth Growth in Guinea Pigs") +
    expand_limits(y=0) +                        # Expand y range
    scale_y_continuous(breaks=0:20*4) +         # Set tick every 4
    theme_bw() +
    theme(legend.justification=c(1,0),
          legend.position=c(1,0))               # Position legend in bottom right	

#############################################
# Bar graphs
#############################################

# Use dose as a factor rather than numeric
tgc2 <- tgc
tgc2$dose <- factor(tgc2$dose)

# Error bars represent standard error of the mean
ggplot(tgc2, aes(x=dose, y=len, fill=supp)) +
    geom_bar(position=position_dodge(), stat="identity") +
    geom_errorbar(aes(ymin=len-se, ymax=len+se),
                  width=.2,                    # Width of the error bars
                  position=position_dodge(.9))

# Use 95% confidence intervals instead of SEM
ggplot(tgc2, aes(x=dose, y=len, fill=supp)) +
    geom_bar(position=position_dodge(), stat="identity") +
    geom_errorbar(aes(ymin=len-ci, ymax=len+ci),
                  width=.2,                    # Width of the error bars
                  position=position_dodge(.9))

## A finished graph might look like this.

ggplot(tgc2, aes(x=dose, y=len, fill=supp)) +
    geom_bar(position=position_dodge(), stat="identity",
             colour="black", # Use black outlines,
             size=.3) +      # Thinner lines
    geom_errorbar(aes(ymin=len-se, ymax=len+se),
                  size=.3,    # Thinner lines
                  width=.2,
                  position=position_dodge(.9)) +
    xlab("Dose (mg)") +
    ylab("Tooth length") +
    scale_fill_hue(name="Supplement type", # Legend label, use darker colors
                   breaks=c("OJ", "VC"),
                   labels=c("Orange juice", "Ascorbic acid")) +
    ggtitle("The Effect of Vitamin C on\nTooth Growth in Guinea Pigs") +
    scale_y_continuous(breaks=0:20*4) +
    theme_bw()

REF:

http://www.cookbook-r.com/Graphs/Plotting_means_and_error_bars_%28ggplot2%29/

http://www.rdocumentation.org/packages/bear/functions/summarySE

http://www.cookbook-r.com/Manipulating_data/Summarizing_data/

http://www.inside-r.org/packages/cran/rmisc/docs/summarySE

时间: 2024-10-01 16:55:22

Plotting means and error bars (ggplot2)的相关文章

Getting started with machine learning in Python

Getting started with machine learning in Python Machine learning is a field that uses algorithms to learn from data and make predictions. Practically, this means that we can feed data into an algorithm, and use it to make predictions about what might

pandas.DataFrame.plot

pandas.DataFrame.plot¶ DataFrame.plot(x=None, y=None, kind='line', ax=None, subplots=False, sharex=None, sharey=False, layout=None, figsize=None, use_index=True, title=None, grid=None, legend=True, style=None, logx=False, logy=False, loglog=False, xt

ggplot2-为图形加入直线

本文更新地址:http://blog.csdn.net/tanzuozhev/article/details/51112057 本文在 http://www.cookbook-r.com/Graphs/Scatterplots_(ggplot2)/ 的基础上加入了自己的理解 对于连续型数据轴和离散型数据轴 # Some sample data dat <- read.table(header=TRUE, text=' cond result control 10 treatment 11.5 '

25个免费的jQuery/ JavaScript的图表和图形库

1.  JS Charts Features Prepare your chart data in XML, JSON or JavaScript Array Create charts in different templates like bar charts, pie charts or simple line graphs You don't need any server-side plugins/modules It's compatible with most web browse

ggplot2-为折线图和条形图添加误差线

本文更新地址: http://blog.csdn.net/tanzuozhev/article/details/51106089 本文在 http://www.cookbook-r.com/Graphs/Plotting_means_and_error_bars_(ggplot2)/ 的基础上加入了自己的理解 采用ggplot2绘制折线图和条形图,并添加误差线. ggplot2只能处理 data.frame数据,每列作为一个变量,是一个指标. 以ToothGrowth数据为例,进行处理 tg <

[C4] Andrew Ng - Improving Deep Neural Networks: Hyperparameter tuning, Regularization and Optimization

About this Course This course will teach you the "magic" of getting deep learning to work well. Rather than the deep learning process being a black box, you will understand what drives performance, and be able to more systematically get good res

python pandas 直方图

import matplotlib.pyplot as plt import numpy as np df2 = pd.Series([1,2,1,4,1],index=[1,2,3,4,5]) # print(df2) #df2.plot() df=pd.DataFrame({1:[1,1,4,3],2:[1,2,3,4]}) #pd.DataFrame.hist(df,column=[1]) #a=df.hist(orientation="vertical",histtype=&q

PLID50 Top-down effects on Perception

Due: 26 November 2019 PLID50 | Lab 4/5Lab 4/5: Top-down effects on PerceptionThese final two laboratory assignments examine a very similar phenomenon: how other cues(e.g., faces, words) affect your perception of speech sounds. Here, you will synthesi

Golang的errno

在C中,出错信息一般通过errno来处理,一般有两种方式,一种是用标准的errno全局变量, 另一种是自己定义错误码,然后在出错时返回错误码.但这里就涉及到一个线程安全的问题. 那在Golang中是如何处理的呢? Golang 和Python一样支持多值返回.和C一样,Golang也可以通过返回错误码来返回错误. 同时Golang也支持CPP等OO里面的异常抛出错误. 多值错误码返回 Golang和Python一样支持多值返回,类似: func swap(a,b int) (int,int)P{