You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用ggplot2与cowplot对齐直方图和密度图失败,仅显示密度图

解决ggplot2+cowplot叠加直方图与密度图仅显示密度图的问题

问题原因

  1. 密度图的绘图背景为白色,叠加时完全覆盖了下方的直方图
  2. 直方图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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.17 11:30:57