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
Plotting means and error bars (ggplot2)的更多相关文章
- R绘图基础
一,布局 R绘图所占的区域,被分成两大部分,一是外围边距,一是绘图区域. 外围边距可使用par()函数中的oma来进行设置.比如oma=c(4,3,2,1),就是指外围边距分别为下边距:4行,左边距3 ...
- DATA VISUALIZATION – PART 2
A Quick Overview of the ggplot2 Package in R While it will be important to focus on theory, I want t ...
- Getting started with machine learning in Python
Getting started with machine learning in Python Machine learning is a field that uses algorithms to ...
- 40 JavaScript Chart and Graph Libraries for Developers--reference
reference:http://www.egrappler.com/javascript-chart-and-graph-libraries-for-developers/ BY TEAMEGRAP ...
- Analysis Guidelines
This section describes some best practices for analysis. These practices come from experience of ana ...
- 方差分析 | ANOVA | 原理 | R代码 | 进阶 | one way and two way
原理 比较两组就用t-test,比较三组及以上就用ANOVA.注意:我们默认说的都是one way ANOVA,也就是对group的分类标准只有一个,比如case和control(ABCD多组),tw ...
- ggplot2-为图形加入直线
本文更新地址:http://blog.csdn.net/tanzuozhev/article/details/51112057 本文在 http://www.cookbook-r.com/Graphs ...
- [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 ...
- 25个免费的jQuery/ JavaScript的图表和图形库
1. JS Charts Features Prepare your chart data in XML, JSON or JavaScript Array Create charts in dif ...
随机推荐
- 【py】配置python环境
首先,在ubuntu 10.10之后的版本中,要这样安装 sudo apt-get install python-pip python-dev build-essential sudo pip ins ...
- 【crunch bang】国内源
/etc/apt/sources.list 因为测试需要,装完Debian7 后,更新为163的源,但是后来装软件时,一些软件依赖包还是装不上.后来把163源稍加改动,就好用了.163源内容如下: d ...
- Yii框架,在页面输出执行sql语句,方便调试
1.下载yiidebugtb,并且放入到 application.extensions.yiidebugtb 目录 2.修改main.php,加入如下代码: 'log'=>array( 'cla ...
- linux_c学习笔记之curl的使用一
参考文档 使用libcurl发送PUT请求上传数据以及DELETE请求删除数据 http://blog.163.com/lixiangqiu_9202/blog/static/535750372014 ...
- listview中item 有checkbox多选防止滑动 listview页面 出现checkbox错位问题
checkbox点击切换背景 <CheckBox android:id="@+id/checkbox" android:layout_width="40dp&quo ...
- JavaSPI机制学习笔记
最近在阅读框架源代码时,常常看到 SPI 的子包, 忍不住查了下: Service Provider Interface : 服务提供接口. JavaSPI 实际上是“基于接口的编程+策略模式+配置文 ...
- java运算符优先级记忆口诀
尊重原创:(口诀)转自http://lasombra.iteye.com/blog/991662 今天看到<java编程思想>中的运算符优先级助记口诀,不过"Ulcer Addi ...
- 【python cookbook】【数据结构与算法】18.将名称映射到序列的元素中
问题:希望通过名称来访问元素,减少结构中对位置的依赖性 解决方案:使用命名元组collections.namedtuple().它是一个工厂方法,返回的是python中标准元组类型的子类,提供给它一个 ...
- DIV设置了固定宽高出现文字(文本)的不能自动换行
如果你的div设置了固定的width和height,有时会出现文字不能自动换行的情况 查过相关资料后才知道,只有英文文本才会出现不能自动换行的情况,(中文不存在)而原因是因为英文文本之间没有加空格,浏 ...
- Symfony电子商务
http://zhilihe.com/content/symfony%E7%94%B5%E5%AD%90%E5%95%86%E5%8A%A1%E9%A1%B9%E7%9B%AE%E6%80%BB%E7 ...