library(ggplot2) #加载ggplot2包
library(dplyr) #加载dplyr包
library(ggstatsplot) #加载ggstatsplot包
diamonds2 <- filter(diamonds, color %in% c('J', 'H')) #选取diamonds数据集中color为J和H的数据,保存为diamonds2
#使用ggplot包的geom_bar函数
diamonds2 %>%
ggplot(aes(x = clarity, fill = color)) + #x轴的分类为clarity,填充颜色为color(J和H)
geom_bar(position = position_fill()) +
scale_fill_brewer(palette = 'Set3') + #设置颜色板
theme_classic() + #设置主题
labs(y = 'Percent') + #设置y轴名为‘Percent’
coord_flip() #旋转坐标轴

#使用ggstatsplot的ggbarstats函数
diamonds2 %>%
ggbarstats(main = color, condition = clarity,
bar.proptest = F, #不显示p值的显著与否
palette = 'Set3',#设置颜色板
results.subtitle = F #副标题不显示统计结果
) +
coord_flip() #旋转坐标轴