[英]Plotting barplots using three categorical variables in R
我的數據框與此類似
df<-read.table (text=" Gender Fruit Food
Male Pear Yes
Female Pear Yes
Male Grape Yes
Female Apple No
Male Grape No
Male Pear No
Male Guba Yes
Male Grape No
Female Apple No
Female Pear Yes
Female Apple Yes
Male Guba No
Female Guba No
Male Pear Yes
Male Apple Yes
Male Pear No
Female Pear Yes
Male Guba No
", header=TRUE)
我想得到一個像這樣的條形圖以及這個 plot 下的表格來顯示數字:
在 plot G、A、G、P 中應閱讀 Grape、Apple、Guba 和 Pear
如果我們可以在這個 plot 下有一個表格來查看這些值,那就太好了。 這已經在 Excel 中簡單地完成了。
使用ggplot
,您需要 map 您對美學或方面感興趣的每個變量。 所以這樣的事情可以工作:
ggplot(df) +
geom_bar(aes(x=Fruit, fill=Food),
position = "dodge") +
facet_wrap(~Gender)
要添加表格,您可以簡單地單獨計算它,然后將其轉換為圖形元素。
p_grph <- ggplot(df) +
geom_bar(aes(x=Fruit, fill=Food),
position = "dodge") +
facet_wrap(~Gender)
p_table <- df %>%
group_by(Gender, Fruit, Food) %>%
summarize(count=n()) %>%
gridExtra::tableGrob()
gridExtra::grid.arrange(p_grph, p_table)
你也可以試試:
library(ggplot2)
library(dplyr)
#Code
df %>% group_by_all() %>% summarise(N=n()) %>%
ggplot(aes(x=Fruit,y=N,fill=Fruit))+
geom_bar(stat = 'identity',
position = position_dodge2(0.9,preserve = 'single'))+
facet_wrap(Gender~Food,scales = 'free',nrow = 1)+
theme(legend.position = 'top')
Output:
如果要添加表格,可以使用patchwork
:
library(patchwork)
#Data for table
Tab <- df %>% group_by_all() %>% summarise(N=n())
#Code
G1 <- df %>% group_by_all() %>% summarise(N=n()) %>%
ggplot(aes(x=Fruit,y=N,fill=Fruit))+
geom_bar(stat = 'identity',
position = position_dodge2(0.9,preserve = 'single'))+
facet_wrap(Gender~Food,scales = 'free',nrow = 1)+
theme(legend.position = 'top')
#Compose
G1+gridExtra::tableGrob(Tab)
Output:
如果您想要下表,您可以通過/
更改+
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.