2009-09-16 8 views
14

Tutti noi amiamo le misure robuste come le mediane e le distanze interquartili, ma lasciamolo fronteggiare, in molti campi, i boxplot non appaiono quasi mai negli articoli pubblicati, mentre i mezzi e gli errori standard lo fanno sempre.Schema di boxplot schmox: come calcolare i mezzi e gli errori standard condizionati da un fattore in R?

È semplice in lattice, ggplot2, ecc. Per disegnare i riquadri e le gallerie sono piene di esse. Esiste un modo altrettanto semplice per disegnare mezzi e errori standard, condizionati da una variabile categoriale?

sto prendendo circa trame come questi:

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

O quelli che vengono chiamati "significa diamanti" di JMP (vedi Figura 3):

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

risposta

14

Il primo lotto era appena coperto in un blog post on imachordata.com. (hat tip to David Smith on blog.revolution-computing.com) Puoi anche read the related documentation from Hadley on ggplot2.

Ecco il codice di esempio:

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() 

Si finisce per assomigliare a questo: alt text http://www.imachordata.com/wp-content/uploads/2009/09/barplot.png

+0

appena mi ha battuto a questo! Ho letto ieri il post di www.imachordata.com e l'ho anche inviato via email a un ex collaboratore. –

+0

È un piccolo mondo nella blogosfera R. :) Recentemente ho iniziato a seguire il pianeta R (http://planetr.stderr.org/), ed è un po 'opprimente. – Shane

+0

Devo smettere di essere pigro e iniziare a mantenere un elenco di blog R. –

0

ggplot produce grafici esteticamente gradevoli, ma non hanno il buon senso per cercare di pubblicare qualsiasi uscita ggplot ancora.

Fino a quando arriva il giorno, ecco come ho realizzato i suddetti grafici. Io uso un pacchetto grafico chiamato "gplots" per ottenere le barre di errore standard (usando i dati che ho già calcolato). Nota che questo codice prevede due o più fattori per ogni classe/categoria. Ciò richiede che i dati vengano inseriti come matrice e per il comando "beside = TRUE" nella funzione "barplot2" per impedire che le barre vengano impilate.

# 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) 

E 'piuttosto semplice-Jane, esteticamente, ma sembra essere quello che la maggior parte delle riviste/vecchi professori vogliono vedere.

Vorrei pubblicare il grafico prodotto da questi dati di esempio, ma questo è il mio primo post sul sito. Scusate. Uno dovrebbe essere in grado di copiare e incollare l'intera cosa (dopo aver installato il pacchetto "gplots") senza problemi.

11

Questa domanda ha quasi 2 anni, ma come nuovo utente R in un campo sperimentale, questa è stata una grande domanda per me, e questa pagina è prominente nei risultati di Google. Ho appena scoperto una risposta che mi piace meglio dell'attuale set, quindi ho pensato di aggiungerla.

il pacchetto sciplot rende l'operazione super facile. Ottiene il lavoro svolto in un unico comando

#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") 

produce questo grafico molto lavorabile con opzioni per lo più predefinite. Nota che le barre di errore sono errori standard per impostazione predefinita, ma il parametro accetta una funzione, quindi possono essere qualsiasi cosa tu voglia! sciplot bargraph.CI with mpg data

8

Arriva un po 'in ritardo al gioco, ma questa soluzione potrebbe essere utile per i futuri utenti. Usa diamond data.frame caricato con R e si avvale di stat_summary insieme a due (super short) funzioni personalizzate.

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