简体   繁体   English

boxplot ggplot2 :: qplot()在同一图R中未分组和分组的数据

[英]boxplot ggplot2::qplot() ungrouped and grouped data in same plot R

My data set features a factor(TypeOfCat) and a numeric (AgeOfCat). 我的数据集包含一个因子(TypeOfCat)和一个数字(AgeOfCat)。

I've made the below box plot. 我做了下面的方框图。 In addition to a box representing each type of cat, I've also tried to add a box representing the ungrouped data (ie the entire cohort of cats and their ages). 除了代表每种类型的猫的方框外,我还尝试添加一个代表未分组数据的框(即整个猫群及其年龄)。 What I've got is not quite what I'm after though, as sum() of course won't provide all the information needed to create such a plot. 我所得到的并不是我想要的,因为sum()当然不会提供创建这样一个绘图所需的所有信息。 Any help would be much appreciated. 任何帮助将非常感激。

Data set and current code: 数据集和当前代码:

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()

Like this? 像这样?

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()

No need for sum . 不需要sum Just take all the values individually for AllCats : 只需单独获取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()

You can see you have all the observations if you add geom_point to the boxplot: 如果将geom_point添加到箱线图中,则可以看到所有观测值:

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

在此处输入图片说明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM