ggplot2柱状图dodge失效求助:柱子叠加无法分离
问题解决:柱状图position_dodge不生效的修复方案
你的问题出在数据格式和geom_col的使用方式上:你用了两个独立的geom_col分别绘制雌雄花序,但ggplot无法识别这是需要并列的分组柱子,所以position_dodge参数没有发挥作用。
修复步骤:
- 把宽格式数据转换为长格式(tidy data),让花序类型成为一个单独的分类变量
- 用单个
geom_col配合fill参数区分组别,此时position_dodge就能正常工作 - 调整双Y轴的数值转换比例,让温度线和柱子的显示更协调
完整修正代码:
# 加载需要的包 library(ggplot2) library(tidyr) # 原始数据 year <- c("sep-2021", "oct-2021", "nov-2021", "dic-2021", "ene-2022", "feb-2022", "mar-2022", "abr-2022", "may-2022", "jun-2022", "jul-2022", "ago-2022", "sep-2022", "oct-2022") temperature <- c(22, 22.2, 23.2, 22, 21.6, 22, 22, 22, 22, 22, 22, 22, 22, 22.4) minflorescences<- c(12, 12, 60, 24, 40, 1, 0, 0,0,0 ,0, 0,0, 37) finflorescences<- c(10, 17, 55, 30, 15, 8, 6, 0, 0, 0, 0, 0, 0, 10) perf<- data.frame(year, temperature, minflorescences, finflorescences) perf$year<- factor(perf$year,levels = unique(perf$year)) # 转换为长格式数据 perf_long <- pivot_longer(perf, cols = c(minflorescences, finflorescences), names_to = "inflorescence_type", values_to = "count") # 绘制图形 ggplot(perf_long) + # 分组柱状图:按inflorescence_type区分,position_dodge生效 geom_col(aes(x = year, y = count, fill = inflorescence_type), position = position_dodge(width = 0.7), colour = "#006000") + # 温度线:调整数值比例让显示更协调,group=1确保连线正确 geom_line(aes(x = year, y = temperature * 3, group = 1), color = "red", size = 1) + # 设置双Y轴:还原温度刻度 scale_y_continuous( name = "花序数量", sec.axis = sec_axis(~ . / 3, name = "Temperature °C") ) + # 设置颜色映射 scale_fill_manual(values = c("minflorescences" = "cyan", "finflorescences" = "magenta")) + labs(title = "月度温度与雌雄花序对比", x = "日期") + theme(axis.text.x = element_text(angle = 45, hjust = 1))
关键说明:
pivot_longer是tidyr包的函数,用来把多列的花序数据合并成两列,这样ggplot能识别分组逻辑position_dodge(width=0.7)调整柱子的间距,数值可以根据需求微调- 温度数据乘以3是为了让线的高度和柱子匹配,sec_axis再除以3把刻度还原成实际温度值,你可以根据数据范围调整这个比例
内容的提问来源于stack exchange,提问作者bryan simba
相关产品推荐
相关产品推荐

