2009-10-29 11 views
13

में प्रत्येक पैनल के लिए अलग-अलग अवरोध के साथ एक लंबवत रेखा जोड़ें I histograms के पैनल बनाने के लिए ggplot2 का उपयोग कर रहा हूं, और मैं प्रत्येक समूह के माध्य पर एक लंबवत रेखा जोड़ने में सक्षम होना चाहता हूं।ggplot2

require("ggplot2") 
# setup some sample data 
N <- 1000 
cat1 <- sample(c("a","b","c"), N, replace=T) 
cat2 <- sample(c("x","y","z"), N, replace=T) 
val <- rnorm(N) + as.numeric(factor(cat1)) + as.numeric(factor(cat2)) 
df <- data.frame(cat1, cat2, val) 

# draws a single histogram with vline at mean 
qplot(val, data=df, geom="histogram", binwidth=0.2) + 
    geom_vline(xintercept=mean(val), color="red") 

# draws panel of histograms with vlines at global mean 
qplot(val, data=df, geom="histogram", binwidth=0.2, facets=cat1~cat2) + 
    geom_vline(xintercept=mean(val), color="red") 

मैं इसे कैसे उपयोग करने के लिए प्रत्येक पैनल के समूह एक्स-अवरोधन के रूप में मतलब है प्राप्त कर सकते हैं: लेकिन geom_vline() प्रत्येक पैनल के लिए एक ही अवरोधन (अर्थात वैश्विक मतलब) का उपयोग करता है? (बोनस पॉइंट्स यदि आप लाइन के आधार पर टेक्स्ट के लेबल को भी जोड़ सकते हैं।)

उत्तर

9

एक तरीका हाथ से पहले मूल्यों के साथ डेटा.फ्रेम बनाना है।

library(reshape) 
dfs <- recast(data.frame(cat1, cat2, val), cat1+cat2~variable, fun.aggregate=mean) 
qplot(val, data=df, geom="histogram", binwidth=0.2, facets=cat1~cat2) + geom_vline(data=dfs, aes(xintercept=val), colour="red") + geom_text(data=dfs, aes(x=val+1, y=1, label=round(val,1)), size=4, colour="red") 
13

मुझे लगता है कि यह @ eduardo की वास्तव में एक पुनर्विक्रय है, लेकिन एक पंक्ति में।

ggplot(df) + geom_histogram(mapping=aes(x=val)) 
    + geom_vline(data=aggregate(df[3], df[c(1,2)], mean), 
     mapping=aes(xintercept=val), color="red") 
    + facet_grid(cat1~cat2) 

alt text http://www.imagechicken.com/uploads/1264782634003683000.png

या (ggplot के लेखक, हैडली द्वारा require(plyr) एक पैकेज) plyr का उपयोग कर:

ggplot(df) + geom_histogram(mapping=aes(x=val)) 
    + geom_vline(data=ddply(df, cat1~cat2, numcolwise(mean)), 
     mapping=aes(xintercept=val), color="red") 
    + facet_grid(cat1~cat2) 

यह नाकाफी लगता है कि vline पहलुओं पर कटौती नहीं है, मैं मुझे यकीन नहीं है क्यों।