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

geom_density结合facet_wrap绘图出现平线,如何排查错误?

问题:geom_density与箱线图结合时出现平线的原因及解决

我尝试结合geom_density与箱线图绘制图形,但得到的是一条完全不符合数据分布的平线。请问我在代码中遗漏了什么问题?

以下是我的R代码:

library(tidyverse)
as_tibble(iris) %>%
  pivot_longer(!Species, names_to = "Measure", values_to = "Value") %>%
  ggplot(aes(Value, Measure)) +
  geom_density() +
  geom_boxplot(width = .25, position = position_nudge(y = -.15), outlier.shape = NA) +
  facet_wrap(~ Species, strip.position = "right", nrow = 3)

核心原因

出现平线是因为geom_density默认的绘制方向和你的坐标系不匹配:

  • 你设置的映射是aes(Value, Measure),x轴是连续数值,y轴是分类变量
  • 默认情况下,geom_density会沿着x轴计算密度并绘制纵向曲线,但在y轴为分类变量的场景下,曲线被挤压成了平线,无法展示每个分类组内的数值分布

解决方法

方法1:指定密度曲线的绘制方向

给geom_density添加orientation = "y"参数,让曲线沿着y轴(分类变量方向)横向绘制,完美匹配当前坐标系:

library(tidyverse)
as_tibble(iris) %>%
  pivot_longer(!Species, names_to = "Measure", values_to = "Value") %>%
  ggplot(aes(Value, Measure)) +
  geom_density(orientation = "y") +  # 关键:指定绘制方向
  geom_boxplot(width = .25, position = position_nudge(y = -.15), outlier.shape = NA) +
  facet_wrap(~ Species, strip.position = "right", nrow = 3)

方法2:调整映射并翻转坐标系

调换x和y的映射关系,再用coord_flip()翻转坐标系,让geom_density默认的绘制方向正常生效:

library(tidyverse)
as_tibble(iris) %>%
  pivot_longer(!Species, names_to = "Measure", values_to = "Value") %>%
  ggplot(aes(Measure, Value)) +
  geom_density() +
  geom_boxplot(width = .25, position = position_nudge(x = -.15), outlier.shape = NA) +
  facet_wrap(~ Species, strip.position = "right", nrow = 3) +
  coord_flip()

额外提示

如果想让密度曲线更贴合箱线图的分布,可以调整geom_density的adjust参数(数值越小曲线越尖锐,越大越平滑);也可以调整密度曲线的颜色、透明度来区分不同组。


内容的提问来源于stack exchange,提问作者maRvin

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.21 19:57:21