2015-02-08 90 views
0

我正在嘗試使分組的barplot發生故障。例如,如果我使用的是mtcars數據集,並且想用「vs」列(第8列)對所有內容進行分組,請查找所有剩餘列的平均值,然後按組對其進行繪製。繪製數據框中每列的平均值/中值按因子分組

下面是我試圖做的一個很差的例子,我知道這是不正確的。

理想情況下,mpg vs vs = 1 & vs = 0將並排排列,其次是cyl並排排列等。我不在乎是否跳過dyplr的聚合或使用ggplot,或者甚至不需要聚合步驟......只是尋找一種方法來做到這一點,因爲它讓我發瘋。

df = mtcars 
agg = aggregate(df[,-8], by=list(df$vs), FUN=mean) 
agg 
barplot(t(agg), beside=TRUE, col=df$vs)) 

回答

2

嘗試

library(ggplot2) 
library(dplyr) 
library(tidyr) 
df %>% 
    group_by(vs=factor(vs)) %>% 
    summarise_each(funs(mean)) %>% 
    gather(Var, Val, -vs) %>% 
    ggplot(., aes(x=Var, y=Val, fill=vs))+ 
    geom_bar(stat='identity', position='dodge') 

enter image description here

或者使用base R

m1 <- as.matrix(agg[-1]) 
row.names(m1) <- agg[,1] 
barplot(m1, beside=TRUE, col=c('red', 'blue'), legend=row.names(m1)) 

enter image description here

相關問題