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

如何消除ggplot绘制的直方图悬浮于x轴上方的间隙?

解决ggplot直方图x轴与y=0基线之间的间隙问题

你可以通过coord_cartesian()函数解决这个问题,别再用ylim()了——ylim()会直接修改数据的取值范围,可能干扰直方图的统计计算;而coord_cartesian()只是调整绘图的显示窗口,不会改变原始数据的统计结果,刚好适配你的需求。

修改后的完整代码:

ggplot(df1, aes(x=Value, color=Type, fill=Type))+ 
  geom_histogram(position="Identity", alpha=0.5)+
  xlab("Loss in MN$")+
  theme_bw()+
  geom_vline(data=mean, aes(xintercept=grp.mean),
             linetype="dashed")+
  scale_fill_manual(values=c("#E52B2B", "#2BE531", "#2BE531"))+
  labs(title="Scenario 1 - Loss Distribution with 1000 different recovery days", subtitle = "Scenario description see text")+
  coord_cartesian(ylim = c(0, NA))  # 新增该行强制y轴从0开始

原理说明:

coord_cartesian(ylim = c(0, NA))里的0指定了y轴下限为0,NA表示保留原始数据计算出的y轴上限,这样既能让直方图底部完全贴合x轴,又不会截断上方的统计结果。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.28 13:27:17