2017-10-19 55 views
1

我的數據集具有一個因子(TypeOfCat)和一個數值(AgeOfCat)。boxplot ggplot2 :: qplot()在同一圖中未分組和分組的數據R

我製作了下面的方塊圖。除了代表每種類型貓的方框之外,我還嘗試添加一個代表未分組數據的方框(即整個貓羣及其年齡)。我所得到的並不完全是我所追求的,因爲sum()當然不會提供創建這種情節所需的全部信息。任何幫助將非常感激。

數據集和當前代碼:

Df1 <- data.frame(TypeOfCat=c("A","B","B","C","C","A","B","C","A","B","A","C"), 
       AgeOfCat=c(14,2,5,8,4,5,2,6,3,6,12,7)) 

Df2 <- data.frame(TypeOfCat=c("AllCats"), 
        AgeOfCat=sum(Df1$AgeOfCat))) 

Df1 <- rbind(Df1, Df2) 

qplot(Df1$TypeOfCat,Df1$AgeOfCat, geom = "boxplot") + coord_flip() 

回答

0

不需要sum。只要把所有的值分別爲AllCats

# Your original code: 
library(ggplot2) 
Df1 <- data.frame(TypeOfCat=c("A","B","B","C","C","A","B","C","A","B","A","C"), 
       AgeOfCat=c(14,2,5,8,4,5,2,6,3,6,12,7)) 
# this is the different part: 
Df2 <- data.frame(TypeOfCat=c("AllCats"), 
        AgeOfCat=Df1$AgeOfCat) 
Df1 <- rbind(Df1, Df2) 

qplot(Df1$TypeOfCat,Df1$AgeOfCat, geom = "boxplot") + coord_flip() 

你可以看到你所有的意見,如果你添加geom_point到箱線圖:

ggplot(Df1, aes(TypeOfCat, AgeOfCat)) + 
    geom_boxplot() + 
    geom_point(color='red') + 
    coord_flip() 

enter image description here

0

喜歡這個?

library(ggplot2) 
# first double your data frame, but change "TypeOfCat", since it contains all: 
df <- rbind(Df1, transform(Df1, TypeOfCat = "AllCats")) 
# then plot it: 
ggplot(data = df, mapping = aes(x = TypeOfCat, y = AgeOfCat)) + 
    geom_boxplot() + coord_flip()