如何优化R语言ggplot2绘制的分组条形图与折线图?
ggplot2分组条形图与折线图优化方案
原代码问题梳理
- 分组条形图:使用
col=Race仅为条形边框上色,未填充条形主体;未对position_dodge设置宽度,易导致条形重叠;Year若为数值型,会被当作连续轴处理,年份显示不够直观。 - 折线图:存在变量名错误(
mutate(Gender=as.factor(Race))应为Race=as.factor(Race));仅用折线展示,数据点不突出,不利于读取具体数值。 - 通用问题:
summarize后残留分组状态,可能影响后续绘图;默认主题样式冗余,缺少数据标签辅助数值读取。
优化后的分组条形图代码
library(ggplot2) library(dplyr) # 预处理数据并绘制分组条形图 df_new2 %>% mutate(Race = as.factor(Race), Year = as.factor(Year)) %>% # 将年份转为因子,作为离散轴展示 group_by(Year, Race) %>% summarize(mean_life = mean(Life_expectancy, na.rm = TRUE), .groups = "drop") %>% # 清理分组,处理缺失值 ggplot(aes(x = Year, y = mean_life, fill = Race)) + # 用fill设置条形填充色 geom_bar(stat = "identity", position = position_dodge(width = 0.8), width = 0.7) + # 调整间距避免条形重叠 geom_text(aes(label = round(mean_life, 1)), # 添加数据标签,保留1位小数 position = position_dodge(width = 0.8), vjust = -0.3, size = 3.5) + labs(title = "2015-2021年不同种族预期寿命均值", subtitle = "分组条形图展示年度差异", x = "年份", y = "预期寿命均值", fill = "种族") + theme_minimal() + # 使用简洁主题 theme(plot.title = element_text(size = 14, face = "bold"), plot.subtitle = element_text(size = 12, color = "#666666"), axis.title = element_text(size = 12), legend.position = "bottom", # 图例移至底部,节省横向空间 panel.grid.major.x = element_blank()) # 隐藏x轴网格线,提升清晰度
优化说明
- 将
Year转为因子,避免连续轴的插值效果,年份显示更符合逻辑 - 用
fill=Race替代col=Race,为条形填充对应种族的颜色,视觉区分更明显 - 设置
position_dodge和条形宽度,解决条形重叠问题 - 添加数据标签,无需读取坐标轴即可获取精确数值
- 清理分组状态,避免后续绘图出现异常
- 调整主题元素,让图表更适配演示场景
优化后的折线图代码
library(ggplot2) library(dplyr) # 预处理数据并绘制折线图 df_new2 %>% mutate(Race = as.factor(Race)) %>% # 修正原代码的变量名错误 group_by(Year, Race) %>% summarize(mean_life = mean(Life_expectancy, na.rm = TRUE), .groups = "drop") %>% ggplot(aes(x = Year, y = mean_life, color = Race, group = Race)) + geom_line(linewidth = 1.2) + # 加粗折线,提升辨识度 geom_point(size = 3) + # 添加数据点,突出年度数值 geom_text(aes(label = round(mean_life, 1)), vjust = -0.8, size = 3.5) + # 添加数据标签 labs(title = "2015-2021年不同种族预期寿命均值变化趋势", subtitle = "折线图展示年度变化", x = "年份", y = "预期寿命均值", color = "种族") + theme_minimal() + theme(plot.title = element_text(size = 14, face = "bold"), plot.subtitle = element_text(size = 12, color = "#666666"), axis.title = element_text(size = 12), legend.position = "bottom")
优化说明
- 修正原代码中变量名错误,避免数据处理异常
- 加粗折线并添加数据点,让趋势变化和具体数值更清晰
- 添加数据标签,便于快速读取每个年份的预期寿命均值
- 调整主题样式,提升整体视觉简洁度
额外优化建议
- 配色方案:使用
scale_fill_brewer(palette = "Set2")或scale_color_brewer(palette = "Set2")替换默认配色,让颜色更和谐专业 - 坐标轴范围:如果预期寿命数值差异较小,可用
ylim()设置合适的y轴范围,放大差异展示 - 字体适配:演示时可添加
theme(text = element_text(family = "Arial"))统一字体,适配投影设备
内容的提问来源于stack exchange,提问作者Priscilla Raj
相关产品推荐
相关产品推荐

