簡體   English   中英

boxplot ggplot2 :: qplot()在同一圖R中未分組和分組的數據

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

我的數據集包含一個因子(TypeOfCat)和一個數字(AgeOfCat)。

我做了下面的方框圖。 除了代表每種類型的貓的方框外,我還嘗試添加一個代表未分組數據的框(即整個貓群及其年齡)。 我所得到的並不是我想要的,因為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()

像這樣?

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

不需要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()

在此處輸入圖片說明

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM