使用ggplot2与cowplot对齐直方图和密度图失败,仅显示密度图
解决ggplot2+cowplot叠加直方图与密度图仅显示密度图的问题
问题原因
- 密度图的绘图背景为白色,叠加时完全覆盖了下方的直方图
- 直方图y轴为频数,密度图y轴为密度,尺度不匹配,导致密度线条可能超出可视范围
修正代码
library(ggplot2) library(cowplot) raises <- attitude$raises df <- data.frame(raises) n <- nrow(df) binwidth <- 1 # 和直方图的binwidth保持一致 # 绘制频数直方图 ph <- ggplot(df, aes(x = raises)) + geom_histogram(binwidth = binwidth, color = "black", fill = "light grey") + scale_x_continuous(breaks = seq(40, 90, by = 10)) + ylim(0, 3) + theme_classic() + # 底层图也设置透明,避免边缘遮挡 theme(panel.background = element_rect(fill = "transparent", color = NA), plot.background = element_rect(fill = "transparent", color = NA)) # 绘制匹配频数尺度的密度图(背景透明) pd <- ggplot(df, aes(x = raises, y = ..density.. * n * binwidth)) + geom_density(color = "red", size = 1) + scale_x_continuous(breaks = seq(40, 90, by = 10)) + scale_y_continuous(expand = expansion(mult = c(0, 0.1)), position = "right", limits = c(0, 3)) + theme_classic() + theme( axis.line.x = element_blank(), axis.title.x = element_blank(), axis.text.x = element_blank(), axis.ticks.x = element_blank(), # 关键:设置背景透明,避免遮挡直方图 panel.background = element_rect(fill = "transparent", color = NA), plot.background = element_rect(fill = "transparent", color = NA), # 区分右侧y轴样式 axis.title.y = element_text(color = "red") ) # 对齐两个图的尺寸 alpl <- align_plots(ph, pd, align = "hv", axis = "tblr") # 完全叠加两个图 ggdraw(alpl[[1]]) + draw_plot(alpl[[2]], x = 0, y = 0, width = 1, height = 1)
关键调整说明
- 透明背景:通过
panel.background和plot.background设置为透明,让下方的直方图可见 - 尺度匹配:用
..density.. * n * binwidth将密度转换为频数,确保密度图线条和直方图的y轴范围一致 - 精准叠加:
draw_plot指定位置和尺寸,保证两个图完全对齐叠加
内容的提问来源于stack exchange,提问作者Alex M
相关产品推荐
相关产品推荐

