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

求助:R ggplot2绘制CDF时曲线超出[1947,2017]范围的解决方法

Fixing ECDF Curve Range in ggplot2

Hey there! I’ve dealt with this exact frustration when plotting ECDFs in ggplot2—let’s get your curve to stay within the [1947, 2017] range properly.

The Problem with xlim()

Your current use of xlim(1947, 2017) is actually filtering out any data points outside that range before the ECDF is calculated. On top of that, stat_ecdf() has a default behavior of extending the curve to the edges of the plot’s x-axis, which is why you’re seeing it spill beyond your desired years.

The Solution: Use coord_cartesian()

Instead of xlim(), use coord_cartesian(xlim = c(1947, 2017)). This function adjusts the visible window of your plot without modifying the underlying data or the ECDF calculation. That means the curve will be computed using all your data, but only the portion within [1947, 2017] will be displayed.

Here’s your modified code:

ggplot(df, aes(x=year)) + 
  stat_ecdf(geom="line") + 
  xlab("Year") + 
  coord_cartesian(xlim = c(1947, 2017))

Bonus: Lock X-Axis Ticks (If Needed)

If you also want to ensure your x-axis ticks don’t go beyond 1947-2017, you can pair coord_cartesian() with scale_x_continuous() to set explicit breaks:

ggplot(df, aes(x=year)) + 
  stat_ecdf(geom="line") + 
  xlab("Year") + 
  coord_cartesian(xlim = c(1947, 2017)) +
  scale_x_continuous(breaks = seq(1947, 2017, by = 10)) # Adjust break interval as needed

This should give you a clean ECDF curve that stays strictly within your desired year range.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.26 09:24:28