Skip to content

Using position_stack() with text geom in stat_summary() #2709

Closed
@aosmith16

Description

@aosmith16

Should it be possible to "stack" text when calculating the labels and the y axis with stat_summary()? I'm getting an error using either position = "stack" or position = position_stack().

library(ggplot2)

# Using stat_summary for aggregation
ggplot(mtcars, aes(x = factor(cyl), y = mpg, fill = factor(am))) + 
    stat_summary_bin(fun.y = sum, geom="bar", position = "stack")+
    stat_summary(aes(label = stat(y)), fun.y = sum,  geom = "text", 
                 position = position_stack(vjust = .5))
#> Error in if (any(negative)) {: missing value where TRUE/FALSE needed

Things work as I expect when doing the calculation outside of ggplot2.

# Aggregation outside ggplot2
suppressPackageStartupMessages( library(dplyr) )
mtsum = mtcars %>%
    group_by(cyl, am) %>%
    summarise(mpg = sum(mpg) )

ggplot(mtcars, aes(x = factor(cyl), y = mpg, fill = factor(am))) + 
    stat_summary_bin(fun.y = sum, geom="bar", position = "stack")+
    geom_text(data = mtsum, aes(label = mpg), position = position_stack(vjust = .5))

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions