简体   繁体   中英

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

My data set features a factor(TypeOfCat) and a numeric (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. 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 . Just take all the values individually for 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:

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

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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