简体   繁体   中英

stat_summary: different behavior between qplot & ggplot2 / understanding the paradigm of ggplot2

I'm sure this is going to be an 'oh geez' simple answer, but I always have trouble understanding the underlying paradigm with ggplot2 (0.9.3). With the following data and helper function:

ltd <- data.frame(r = c(rnorm(5, 5, 1.5), rnorm(5, 8, 2)),
    f1 = c(rep("L", 5), rep("H", 5)))

seXy <- function (x) {
    m <- mean(na.omit(x))
    se <- sd(x, na.rm = TRUE)/sqrt(length(na.omit(x)))
    u <- m + se
    l <- m - se
    c(y = m, ymin = l, ymax = u)
    }

This qplot request works fine:

tp <- qplot(x = f1, y = r, data = ltd, geom = "point")
tp <- tp + stat_summary(fun.data = "seXy", color = "red", geom = "linerange")
print(tp)

But this ggplot2 request does not draw the linerange, and does not give an error (and using the alternative commented line or not does not do anything different):

tp <- ggplot()
tp <- tp + geom_point(aes(x = f1, y = r), data = ltd)
#tp <- tp + stat_summary(fun.data = "seXy", color = "red", geom = "linerange")
tp <- tp + stat_summary(fun.data = "seXy", color = "red", geom = "linerange", 
        aes(ymin = ..ymin.., ymax = ..ymax..))
print(tp)

What does the second approach need to make the linerange show up? I clearly misunderstand something. Of course, this is a MWE and the real context is more complex, but I can't troubleshoot that w/o understanding this simple example. Looks like qplot is doing something for me in the background but I don't know what. Thanks.

Problem could be that you define data only in geom_point() and so stat_summary() do not use them.

If you put data and aes() in ggplot() function, then stat_summary() gives linerange .

ggplot(ltd,aes(x = f1, y = r))+geom_point()+
  stat_summary(fun.data = "seXy", color = "red", geom = "linerange")

The same result is achieved if data and aes() is defined inside stat_summary()

tp <- ggplot()
tp <- tp + geom_point(aes(x = f1, y = r), data = ltd)
tp <- tp + stat_summary(data=ltd,aes(x = f1, y = r),fun.data = "seXy", color = "red", geom = "linerange")
print(tp)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM