如何用ggplot2绘制堆叠柱状图+双折线图的组合图表
解决方案:堆叠柱状图+双折线图组合绘制
要实现堆叠柱状(chromosome、plasmid)与双折线(gc、cds)的组合图表,需利用ggplot2的双Y轴功能适配不同数据量级,以下是修改后的完整代码:
# 加载所需包 library(readxl) library(ggplot2) library(dplyr) library(reshape2) # 替换原reshape包,兼容性更稳定 # 读取数据 years_data <- read_excel("D:/menuscript/forgraph.xlsx", sheet = "data") years_data <- as.data.frame(years_data) # 1. 绘制堆叠柱状图主图层(仅chromosome和plasmid) p <- ggplot() + geom_bar( data = years_data %>% select(Year, chromosome, plasmid) %>% melt(id.vars = "Year"), aes(x = Year, y = value, fill = variable), stat = "identity", position = "stack" ) + labs(x = "Year", y = "Chromosome/Plasmid Count", fill = "Type") + ggtitle("Counts & GC/CDS Trends by Year") + scale_x_continuous(breaks = years_data$Year) + theme(axis.text.x = element_text(angle = 45, vjust = 1, hjust = 1)) # 优化X轴标签显示位置 # 2. 处理折线图数据(gc和cds) line_data <- years_data %>% select(Year, gc, cds) %>% melt(id.vars = "Year") # 计算缩放系数:让gc百分比适配右侧Y轴的量级(可根据实际数据调整) cds_max <- max(years_data$cds) bar_sum_max <- max(rowSums(years_data[, c("chromosome", "plasmid")])) gc_scale <- cds_max / max(years_data$gc) # 3. 添加双折线图层+右侧Y轴 p <- p + # gc折线(缩放后适配右侧轴) geom_line(data = line_data %>% filter(variable == "gc"), aes(x = Year, y = value * gc_scale, color = variable), linewidth = 1) + geom_point(data = line_data %>% filter(variable == "gc"), aes(x = Year, y = value * gc_scale, color = variable), size = 2) + # cds折线(直接用原数值) geom_line(data = line_data %>% filter(variable == "cds"), aes(x = Year, y = value, color = variable), linewidth = 1) + geom_point(data = line_data %>% filter(variable == "cds"), aes(x = Year, y = value, color = variable), size = 2) + # 设置右侧双刻度Y轴 scale_y_continuous( sec.axis = sec_axis( ~ . / gc_scale, name = "GC(%) / CDS Count", breaks = c(seq(0, max(years_data$gc), 2), seq(0, cds_max, 500)) ) ) + # 自定义颜色区分不同元素 scale_fill_manual(values = c("chromosome" = "#2E86AB", "plasmid" = "#F2D388")) + scale_color_manual(values = c("gc" = "#C94C4C", "cds" = "#8D93AB")) + # 调整图例布局 guides(fill = guide_legend(order = 1), color = guide_legend(order = 2)) + theme(plot.title = element_text(hjust = 0.5), legend.position = "bottom") # 显示图表 print(p)
核心要点说明
- 数据拆分:将柱状图和折线图的数据分开处理,避免不同类型数据的混淆
- 双Y轴适配:通过缩放系数让gc百分比与cds计数、柱状图数值的量级匹配,确保右侧轴能同时展示两种数据
- 图层顺序:先绘制柱状图再叠加折线图,防止折线被遮挡
- 样式优化:自定义颜色、调整X轴标签角度和图例位置,提升图表可读性
内容的提问来源于stack exchange,提问作者chinmaya mahakul
相关产品推荐
相关产品推荐

