2009-09-16 6 views
14

우리 모두는 중선 및 사 분위 범위와 같은 강력한 측정법을 좋아하지만 많은 분야에서 박스 플롯이 게시 된 기사에 거의 표시되지 않는 반면 수단과 표준 오류는 항상 그렇습니다.Boxplot schmoxplot : R의 요소로 조건화 된 평균과 표준 오차를 그리는 방법?

상자 그림을 그릴 때 격자, ggplot2 등으로 간단하며 갤러리가 가득합니다. 범주 형 변수에 의해 조절되는 수단과 표준 오류를 그릴 수있는 똑같은 방법이 있습니까?

나는이 같은 플롯에 대해 복용 해요 :

http://freakonomics.blogs.nytimes.com/2008/07/30/how-big-is-your-halo-a-guest-post/

또는 무엇이라고는 JMP에서 "다이아몬드를 의미한다"(그림 3 참조)

http://blogs.sas.com/jmp/index.php?/archives/127-What-Good-Are-Error-Bars.html

답변

14

첫 번째 플롯을 방금 blog post on imachordata.com로 덮여있었습니다. (모자 끝은 David Smith on blog.revolution-computing.com) read the related documentation from Hadley on ggplot2 일 수도 있습니다.

library(ggplot2) 
data(mpg) 

#create a data frame with averages and standard deviations 
hwy.avg<-ddply(mpg, c("class", "year"), function(df) 
return(c(hwy.avg=mean(df$hwy), hwy.sd=sd(df$hwy)))) 

#create the barplot component 
avg.plot<-qplot(class, hwy.avg, fill=factor(year), data=hwy.avg, geom="bar", position="dodge") 

#first, define the width of the dodge 
dodge <- position_dodge(width=0.9) 

#now add the error bars to the plot 
avg.plot+geom_linerange(aes(ymax=hwy.avg+hwy.sd, ymin=hwy.avg-hwy.sd), position=dodge)+theme_bw() 

그것은이처럼 보이는 끝 : 여기

은 예제 코드입니다 alt text http://www.imachordata.com/wp-content/uploads/2009/09/barplot.png

+0

당신은 그냥 날이 하나 이길! 나는 어제 www.imachordata.com 글을 읽었고 이전 동료에게 이메일로 이메일을 보냈다. –

+0

R 블로그 세계에서 작은 세계입니다. :) 나는 최근 행성 R (http://planetr.stderr.org/)에 뒤이어 시작했고, 약간 압도적이다. – Shane

+0

게으르지 않고 R 블로그 목록을 관리하기 시작해야합니다. –

0

ggplot이 심미적으로 만족 그래프를 생성한다, 그러나 나는 시도하고 ggplot 출력을 게시 할 수있는 진취성이없는 아직.

하루가 올 때까지, 내가 어떻게 앞에서 설명한 그래프를 작성했는지가 나와 있습니다. 나는 'gplots'라는 그래픽 패키지를 사용하여 표준 오류 막대를 얻습니다 (이미 계산 한 데이터 사용). 이 코드는 각 클래스/카테고리에 대해 둘 이상의 요소를 제공합니다. 이렇게하려면 데이터가 행렬로 들어가야하고 "barplot2"함수의 "beside = TRUE"명령에 대해 막대가 쌓이지 않도록해야합니다.

# Create the data (means) matrix 
# Using the matrix accommodates two or more factors for each class 

data.m <- matrix(c(75,34,19, 39,90,41), nrow = 2, ncol=3, byrow=TRUE, 
       dimnames = list(c("Factor 1", "Factor 2"), 
           c("Class A", "Class B", "Class C"))) 

# Create the standard error matrix 

error.m <- matrix(c(12,10,7, 4,7,3), nrow = 2, ncol = 3, byrow=TRUE) 

# Join the data and s.e. matrices into a data frame 

data.fr <- data.frame(data.m, error.m) 

# load library {gplots} 

library(gplots) 

# Plot the bar graph, with standard errors 

with(data.fr, 
    barplot2(data.m, beside=TRUE, axes=T, las=1, ylim = c(0,120), 
       main=" ", sub=" ", col=c("gray20",0), 
        xlab="Class", ylab="Total amount (Mean +/- s.e.)", 
       plot.ci=TRUE, ci.u=data.m+error.m, ci.l=data.m-error.m, ci.lty=1)) 

# Now, give it a legend: 

legend("topright", c("Factor 1", "Factor 2"), fill=c("gray20",0),box.lty=0) 

꽤 일반 제인, 미학적,하지만 대부분의 저널/오래된 교수가보고 싶은 것으로 보인다.

나는이 예제 데이터에 의해 생성 된 그래프를 게시 하겠지만 이것은 사이트의 첫 번째 게시물입니다. 죄송합니다. 하나는 문제없이 "gplots"패키지를 설치 한 후 전체를 복사하여 붙여 넣을 수 있어야합니다.

11

이 질문은 거의 2 살이지만 실험 분야에서 새로운 R 사용자로서 큰 질문이었습니다.이 페이지는 Google 검색 결과에서 두드러졌습니다. 방금 내가 현재 세트보다 더 좋아 보이는 답을 발견 했으므로 추가 할 것이라고 생각했습니다.

패키지 sciplot은 작업을 매우 쉽게 만듭니다. 단일 명령으로 작업을 완료합니다.

#only necessary to get the MPG dataset from ggplot for direct comparison 
library(ggplot2) 
data(mpg) 
attach(mpg) 

#the bargraph.CI function with a couple of parameters to match the ggplot example 
#see also lineplot.CI in the same package 
library(sciplot) 
bargraph.CI(
    class, #categorical factor for the x-axis 
    hwy, #numerical DV for the y-axis 
    year, #grouping factor 
    legend=T, 
    x.leg=19, 
    ylab="Highway MPG", 
    xlab="Class") 

대부분의 기본 옵션이있는이 매우 실행 가능한 그래프가 생성됩니다. 오류 막대는 기본적으로 표준 오류이지만 매개 변수는 함수를 사용하므로 원하는대로 지정할 수 있습니다. sciplot bargraph.CI with mpg data

8

게임에 다소 늦게 도착하지만이 솔루션은 이후 사용자에게 유용 할 수 있습니다. R로로드 된 diamond data.frame을 사용하며 stat_summary과 2 개의 (초 단정) 사용자 정의 함수를 사용합니다.

require(ggplot2) 

# create functions to get the lower and upper bounds of the error bars 
stderr <- function(x){sqrt(var(x,na.rm=TRUE)/length(na.omit(x)))} 
lowsd <- function(x){return(mean(x)-stderr(x))} 
highsd <- function(x){return(mean(x)+stderr(x))} 

# create a ggplot 
ggplot(diamonds,aes(cut,price,fill=color))+ 
# first layer is barplot with means 
stat_summary(fun.y=mean, geom="bar", position="dodge", colour='white')+ 
# second layer overlays the error bars using the functions defined above 
stat_summary(fun.y=mean, fun.ymin=lowsd, fun.ymax=highsd, geom="errorbar", position="dodge",color = 'black', size=.5) 

bar + error plot http://i41.tinypic.com/ief48o.png