2011-09-28 31 views
0

我在創建用ggplot創建的背對背直方圖的方面網格時遇到了一些麻煩。背對背直方圖失敗的facet_grid

# create data frame with latency values 
latc_sorted <- data.frame( 
subject=c(1,1,1,1,1,2,2,2,2,2), 
grp=c("K_N","K_I","K_N","K_I","K_N","K_I","K_N","K_I","K_N","K_I"), 
lat=c(22,45,18,55,94,11,67,22,64,44)  
) 

# subset and order data 
x.sub_ki<-subset(latc_sorted, grp=="K_I") 
x.sub_kn<-subset(latc_sorted, grp=="K_N") 
x.sub_k<-rbind(x.sub_ki,x.sub_kn) 
x=x.sub_ki$lat 
y=x.sub_kn$lat 
nm<-list("x","y") 

# make absolute values on x axis 
my.abs<-function(x){abs(x)} 

# plot back-to-back histogram 
hist_K<-qplot(x, geom="histogram", fill="inverted", binwidth=20) + 
geom_histogram(data=data.frame(x=y), aes(fill="non-inverted", y=-..count..), 
binwidth= 20) + scale_y_continuous(formatter='my.abs') + coord_flip() + 
scale_fill_hue("variable") 

hist_K 

此地塊正常,但如果我嘗試以下我得到的錯誤: 錯誤:鑄造配方中含有不熔化的數據中發現的變量:x.sub_k $主題

hist_K_sub<-qplot(x, geom="histogram", fill="inverted", binwidth=20) + 
geom_histogram(data=data.frame(x=y), aes(fill="non-inverted", y=-..count..), 
binwidth= 20) + scale_y_continuous(formatter='my.abs') + coord_flip() + 
scale_fill_hue("variable")+ 
facet_grid(x.sub_k$subject ~ .) 

hist_K_sub 

任何想法是什麼導致這失敗?

回答

1

問題是在傳遞到各個圖層的data.frames中查找在facet_grid中引用的變量。您已創建(隱式和顯式)data.frames只有lat數據並沒有subject信息。如果您使用的是x.sub_kix.sub_kn,則它們確實具有與lat值關聯的subject變量。

hist_K_sub <- 
ggplot() + 
    geom_histogram(data=x.sub_ki, aes(x=lat, fill="inverted",  y= ..count..), binwidth=20) + 
    geom_histogram(data=x.sub_kn, aes(x=lat, fill="not inverted", y=-..count..), binwidth=20) + 
    facet_grid(subject ~ .) + 
    scale_y_continuous(formatter="my.abs") + 
    scale_fill_hue("variable") + 
    coord_flip() 

hist_K_sub 

hist_K_sub

我還從qplot轉換爲完全ggplot語法;這表明ki和kn的平行結構更好。

+0

感謝布賴恩,這是完美的! – FGiorlando

0

上面的語法不GGPLOT2的較新版本的工作,使用 而不是下面的軸的格式:

abs_format <- function() { 
function(x) abs(x) 
} 

hist_K_sub <- hist_K_sub+ scale_y_continuous(labels=abs_format())