求助:R ggplot2绘制CDF时曲线超出[1947,2017]范围的解决方法
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

