'Restrict X axis after stat_ecdf in ggplot?

How do I change the X axis of stat_ecdf, but not change the calculation of ecdf?

Example code:

df <- data.frame(x=c(1,2,3,4,5))

# 1 to 5
ggplot(df, aes(x)) + stat_ecdf()

# 1 to 3, but stat_ecdf no longer calculated on the whole range
ggplot(df, aes(x)) + stat_ecdf() + scale_x_continuous(limits=c(NA,3))

The first graph gets to 1.0 by 5, as I'd expect:

1 to 5

The second graph goes from 1 to 3 (good), but ends up at y=1 instead of y=0.66:

1 to 3

This is likely because the stat_ecdf has been calculated over the visible window, but I want it calculated over all the data.

I'm pretty sure I've asked this before, but I can't find it.



Solution 1:[1]

In general, the points are removed before the summary statistics are calculated. Using coord_cartesian() gets around this. Try:

ggplot(df, aes(x)) + stat_ecdf() +
  coord_cartesian(xlim = c(0, 3))

Solution 2:[2]

My guess is that you're missing the aesthetics ymin and ymax that geom_ribbon requires. You might try:

    Graph <-  ggplot(df, aes(x = var_x, fill = year, ymin = ..y..-0.1, ymax = ..y..+0.1)) + 
    stat_ecdf( geom = "ribbon") +
    coord_cartesian(xlim = c(0, 3))

If that doesn't work, you might reply with the data frame, df, you're using and the error message you see. Thanks, Eugene

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 dfrankow
Solution 2 eugene100hickey