Skip to content

stat_summary transforms first before applying summary function (rather than vice versa) #2804

Closed

Description

@coolbutuseless

I expected stat_summary to summarise data first then transform the summary for display.

What actually happens: the data is transformed and then the summary is calculated.

In the reprex below, the mean at x=0 is definitely 1, but when you use a transformed axis, the mean of the transformed values doesn't match that (because the mean of the transformed data is different from the transform of the mean of the data).

Is my expectation wrong here on the order of operations? Should I be doing something completely different to achieve my goal?

Is this is a ggplot2 bug? a feature? a limitation of the architecture/grammar-of-graphics? Or am I just doing the wrong thing?

library(tidyverse)

plot_df <- data.frame(
  x = rep(1:3, each=7),
  y = c(0, 0, 0, 0, 1, 1, 5,    1, 1, 1, 1, 2, 2, 2,      2, 3, 4, 5, 6, 7, 8)
)


p <- ggplot(plot_df, aes(x, y)) +
  geom_point(alpha=0.4) +
  stat_summary(fun.y = mean, geom='line') +
  theme_bw()


# The linear version correctly shows mean at x=0 is 1
p + scale_y_continuous(breaks=1:9) +
  ggtitle("Using stat_summary to draw a mean line\nNote: at x=1 mean=1 (correct)")

# Transformed axis version has incorrect mean at x=0
p + scale_y_sqrt(breaks=1:9) +
  ggtitle("Using stat_summary to draw a mean line\nNow with transformed y axis\nNote: at x=1  mean != 1 (incorrect)")

Created on 2018-08-05 by the reprex
package
(v0.2.0).

Activity

  1. eliocamp commented on Aug 5, 2018

    @eliocamp
    Contributor

    I think that for that case you need to apply the transform in the coordinates, not on the scales. This seems to work.

    library(ggplot2)
    
    plot_df <- data.frame(
      x = rep(1:3, each=7),
      y = c(0, 0, 0, 0, 1, 1, 5,    1, 1, 1, 1, 2, 2, 2,      2, 3, 4, 5, 6, 7, 8)
    )
    
    
    p <- ggplot(plot_df, aes(x, y)) +
      geom_point(alpha=0.4) +
      stat_summary(fun.y = mean, geom='line') +
      theme_bw()
    
    p + coord_trans(y = "sqrt")

    Created on 2018-08-05 by the reprex package (v0.2.0).

  2. coolbutuseless commented on Aug 5, 2018

    @coolbutuseless
    ContributorAuthor

    I was just about to update this issue with that plot :)

    I don't want the curved lines that this gives. Which makes me think I should stick with my current custom geom/stat.

    But I'm interested to see if there's a way to switch the transform/summary ordering, or if the maintainers are interested in such a PR.

  3. eliocamp commented on Aug 5, 2018

    @eliocamp
    Contributor

    Mh, that's a tough one.
    I think the curved line is technically a more correct representation of the data, but I can see why you might want to have it straight. In that case, you might have to compute the summary yourself first an then do it by hand? If you have enough ggplot2 mad skillz then a custom geom/stat might do the trick, yes.

    The idea that statistics are computed on the scaled data seems to be part of the foundations of the Grammar of Graphics, so I think it's unlikely that this would change.
    This is from Wilkinson's book:
    image

    Of course, I can't speak on behalf of the ggteam so I'll let them answer.

  4. coolbutuseless commented on Aug 5, 2018

    @coolbutuseless
    ContributorAuthor

    @eliocamp I thought that might be the case - i.e. the order of ops is set by the grammar of graphics which means that the thing I want to do is "disallowed"

    In my custom stat/geom I've worked around it by using the scales$y$trans$inverse to apply the inverse transform to the data and then work on that. This won't work when a transform isn't completely invertible.

    The new idea i'm looking at is asking ggplot2::transform_df() function to keep the original values as well as the transformed ones. Then I use a flag to ask stat_summary to calculate on the original values rather than the transformed ones.

    This probably wrecks the purity of the grammar workflow

  5. clauswilke commented on Aug 5, 2018

    @clauswilke
    Member

    You could always use a summary function that undoes the coordinate transformation. Though I would probably just summarize beforehand using dplyr. In any case, I don't see the need for changes in the ggplot2 code base.

    library(ggplot2)
    
    plot_df <- data.frame(
      x = rep(1:3, each=7),
      y = c(0, 0, 0, 0, 1, 1, 5,    1, 1, 1, 1, 2, 2, 2,      2, 3, 4, 5, 6, 7, 8)
    )
    
    ggplot(plot_df, aes(x, y)) +
      geom_point(alpha=0.4) +
      stat_summary(fun.y = function(x) sqrt(mean(x^2)), geom='line') +
      scale_y_sqrt(breaks=1:9) +
      theme_bw()

    Created on 2018-08-05 by the reprex package (v0.2.0).

  6. coolbutuseless commented on Aug 5, 2018

    @coolbutuseless
    ContributorAuthor

    Hi @clauswilke

    Summarising beforehand in dplyr isn't convenient when you may be facetting/grouping and drawing multiple lines. It then means you have to keep your dplyr group_by/summarisation code in sync with your ggplot facetting/grouping code - which will be error prone.

    And the idea of a function that undoes the coordinate transform is what I (sort of) currently do, but this fails when the transform creates infinities (which are thrown away by default in compute_layer).

    e.g. if we do a log transform on the y axis, then all the zeros become infinities and are removed from the stat calculation, and we get the incorrect mean at x=1 is (5+1+1)/3 = 2.3

    library(ggplot2)
    
    plot_df <- data.frame(
      x = rep(1:3, each=7),
      y = c(0, 0, 0, 0, 1, 1, 5,    1, 1, 1, 1, 2, 2, 2,      2, 3, 4, 5, 6, 7, 8)
    )
    
    
    ggplot(plot_df, aes(x, y)) +
      geom_point(alpha=0.4) +
      stat_summary(fun.y = function(x) log10(mean(10^x)), geom='line') +
      scale_y_log10(breaks=1:9) +
      theme_bw()
    #> Warning: Transformation introduced infinite values in continuous y-axis
    
    #> Warning: Transformation introduced infinite values in continuous y-axis
    #> Warning: Removed 4 rows containing non-finite values (stat_summary).

    Created on 2018-08-06 by the reprex
    package
    (v0.2.0).

  7. hadley commented on Aug 6, 2018

    @hadley
    Member

    You’re asking for a fundamental change to the way that ggplot2 works for a fairly small enhancement that can be achieved with dplyr. The cost-benefit ratio of this proposed change means that it’s not a good fit for ggplot2.

  8. coolbutuseless commented on Aug 6, 2018

    @coolbutuseless
    ContributorAuthor

    Hi @clauswilke, @hadley

    Fair enough.

    Would you be open to considering a small change in an internal data structure which would allow 3rd parties to access the original untransformed data in custom Stats/Geoms?

    Something like this change in scales_transform_df which would keep the original data during the scaling process?

    scales_transform_df <- function(scales, df) {
      if (ggplot2:::empty(df) || length(scales$scales) == 0) return(df)
    
      transformed <- unlist(lapply(scales$scales, function(s) s$transform_df(df = df)),
        recursive = FALSE)
    
      # Keep copies of original/untransformed vars
      varnames <- names(transformed)
      orig <- df[varnames]
      colnames(orig) <- paste(varnames, "orig", sep='.')
    
      plyr::quickdf(c(transformed, df[setdiff(names(df), names(transformed))], orig))
    }
  9. lock commented on Feb 2, 2019

    @lock

    This old issue has been automatically locked. If you believe you have found a related problem, please file a new issue (with reprex) and link to this issue. https://reprex.tidyverse.org/

  10. locked and limited conversation to collaborators on Feb 2, 2019
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions