2017-10-19 71 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()