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

如何使ggplot2绘制的密度图曲线从y=0起始?

让ggplot2密度图曲线从y=0起始

你的当前运行结果:
当前运行结果

期望的输出效果:
期望输出效果

要实现密度图曲线从y=0开始的效果,只需在geom_density()中添加boundary参数,将其设置为x变量的最小值即可。这个参数会指定密度估计的边界,让曲线在数据起始点处从y=0开始绘制,与直方图的起始位置对齐。

修改后的代码(适配你的数据集)

ggplot(irrigation_data, aes(x = Temperature)) +
  geom_histogram(aes(y = after_stat(density)), binwidth = 2, fill = "lightblue") +
  geom_density(color = "blue", size = 1, boundary = min(irrigation_data$Temperature)) +
  labs(title = "Soil Temperature Distribution",
       x = "Temperature (°C)",
       y = "Density") +
  theme_minimal()

可复现示例验证

用你提供的测试数据验证修改效果:

library(ggplot2)
set.seed(101) 
dd <- data.frame(Temperature = runif(1000, min = 0, max = 45)) 

ggplot(dd, aes(x = Temperature)) + 
    geom_histogram(aes(y = after_stat(density)), binwidth = 2) + 
    geom_density(boundary = min(dd$Temperature))

这样修改后,密度曲线就会从x轴的最小值位置(y=0)开始,完全匹配你期望的可视化效果。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.14 18:05:07