R编程新手求助:用ggplot2绘制指定数据格式的堆叠柱状图
嘿,作为R新手碰到这种需要先统计再绘图的问题太正常啦,我来一步步带你搞定!
从数据统计到堆叠柱状图的完整方案
你需要先统计每个state下不同type的出现次数,再用ggplot2绘制堆叠柱状图,下面是具体步骤:
1. 先把数据转换成R能识别的数据框
首先把你给出的原始数据整理成数据框:
# 创建数据框 df <- data.frame( s_no = c("t1", "t2", "t3", "t4", "t5", "t6", "t7", "t8", "t9", "t10"), type = c("type1", "type2", "type3", "type1", "type3", "type3", "type3", "type2", "type2", "type2"), state = c("A", "C", "A", "B", "B", "B", "C", "A", "C", "B") )
2. 统计各state和type的计数
这里推荐用dplyr包的count()函数,简单直观,新手好上手。如果还没装这个包,先安装:
install.packages("dplyr") library(dplyr) # 按state和type分组,计算每组的数量 count_df <- df %>% count(state, type, name = "count") # name参数用来指定计数列的名字
要是你不想用dplyr,也可以用base R的原生方法:
# base R统计方式 table_result <- table(df$state, df$type) count_df <- as.data.frame(table_result) colnames(count_df) <- c("state", "type", "count")
3. 用ggplot2绘制堆叠柱状图
现在有了统计好的计数数据,就可以画图啦。先确保ggplot2已经安装:
install.packages("ggplot2") library(ggplot2) # 绘制基础堆叠柱状图 ggplot(count_df, aes(x = state, y = count, fill = type)) + geom_col() + # 默认就是堆叠模式,position="stack"可以省略 labs(title = "各State下Type的分布", x = "State", y = "计数") + theme_minimal()
fill = type是告诉ggplot用type来区分堆叠的不同部分geom_col()适合已经统计好计数的数据(如果直接用原始数据,也可以用geom_bar(stat = "count"),不过我们提前统计过,用geom_col更高效)
加分小技巧:给柱子加上计数标签
要是想让每个堆叠部分的数量显示在柱子里,可以加上geom_text():
ggplot(count_df, aes(x = state, y = count, fill = type)) + geom_col() + geom_text(aes(label = count), position = position_stack(vjust = 0.5)) + # 让标签居中显示 labs(title = "各State下Type的分布(带计数标签)", x = "State", y = "计数") + theme_minimal()
这样就能得到你想要的堆叠柱状图啦,一步步拆解下来是不是没那么难了~
内容的提问来源于stack exchange,提问作者Nidheesh
相关产品推荐
相关产品推荐

