求助:在R中绘制对比两等级的Side by side barplots(并排条形图)
在R中绘制并排条形图(Side by Side Barplots)
1. 数据格式转换
你的数据集属于宽格式(每列对应一个等级),而ggplot2更适配长格式数据,第一步需要完成格式转换:
- 先加载
tidyverse包(整合了ggplot2、dplyr、tidyr等工具) - 用示例代码模拟并转换数据(替换成你实际的数据集即可)
# 加载工具包 library(tidyverse) # 模拟你的数据集结构 df <- data.frame( Category = c("A", "B", "C", "D"), # 对应你的类别列 Grade1 = c(10, 20, 15, 25), # 第一个等级的数值 Grade2 = c(15, 18, 22, 20) # 第二个等级的数值 ) # 转换为长格式 df_long <- df %>% pivot_longer(cols = -Category, names_to = "Grade", values_to = "Value")
2. 绘制基础并排条形图
通过position = position_dodge()实现条形并排效果,核心代码如下:
ggplot(df_long, aes(x = Category, y = Value, fill = Grade)) + geom_bar(stat = "identity", position = position_dodge(width = 0.8), width = 0.7) + # 添加标题与坐标轴标签 labs(title = "不同类别下两个等级的数值对比", x = "类别", y = "数值", fill = "等级") + # 可选:设置简洁主题 theme_minimal() + # 可选:自定义填充色 scale_fill_brewer(palette = "Set2")
3. 细节优化(按需调整)
如果需要在条形上方显示数值标签,添加geom_text()即可:
ggplot(df_long, aes(x = Category, y = Value, fill = Grade)) + geom_bar(stat = "identity", position = position_dodge(width = 0.8), width = 0.7) + # 添加数值标签 geom_text(aes(label = Value), position = position_dodge(width = 0.8), vjust = -0.5, size = 3.5) + labs(title = "不同类别下两个等级的数值对比", x = "类别", y = "数值", fill = "等级") + theme_minimal() + scale_fill_brewer(palette = "Set2")
你可以根据需求调整条形宽度、颜色主题、标签位置等参数,匹配预期的可视化效果。
内容的提问来源于stack exchange,提问作者dobiii
相关产品推荐
相关产品推荐

