Skip to content

cant combine group with color or fill aesthetics for geom_density #3804

@ColeGC

Description

@ColeGC

When using the group aesthetic in combination with either fill or color aesthetic, the fill/color aesthetic appears to be ignored (with geom_density and geom_histogram).

The color/fill aesthetic is recognized and behaves as expected if the group aesthetic is also used for faceting. Using the color and fill aesthetic in combination works as expected. Specifying color + fill + group together in combination results in the aesthetic that is not shared with group being ignored.

library(ggplot2)

n_sims <- 10
n_obs <- 100
delta <- 1
tbl <- data.frame("iter" = rep(rep(paste0("s", 1:n_sims), each = n_obs), times = 2),
                  "type" = rep(c("base", "compare"), each = n_obs*n_sims),
                  "val" = c(rnorm(n_sims*n_obs, mean = 0, sd = 1), rnorm(n_sims*n_obs, mean = delta, sd = 1)))

# Want to plot density of 'val', for each type-iter combination; with some coloring to indicate 'type'
# Using group with fill or color aesthetic leads to only group being used (for both geom_density and geom_histogram)
ggplot(tbl, aes(x = val, fill = type, group = iter)) + 
  geom_density()

ggplot(tbl, aes(x = val, color = type, group = iter)) + 
  geom_density()

ggplot(tbl, aes(x = val, fill = type, group = iter)) + 
  geom_histogram()
#> `stat_bin()` using `bins = 30`. Pick better value with `binwidth`.

# Using fill + color aesthetics works
ggplot(tbl, aes(x = val, fill = type, color = iter)) + 
  geom_density(alpha = 0.25)

# Using all group, fill, and color aesthetics leads to the aesthetic not shared with group being
ggplot(tbl, aes(x = val, fill = type, color = iter, group = iter)) + 
  geom_density(alpha = 0.25)

ggplot(tbl, aes(x = val, fill = iter, color = type, group = iter)) + 
  geom_density(alpha = 0.25)

ggplot(tbl, aes(x = val, fill = type, color = iter, group = type)) + 
  geom_density(alpha = 0.25)

ggplot(tbl, aes(x = val, fill = iter, color = type, group = type)) + 
  geom_density(alpha = 0.25)

# Using fill + group aeasthetics works when combined with facet_grid
ggplot(tbl, aes(x = val, fill = type, group = iter)) + 
  geom_density(alpha = 0.25) + 
  facet_grid(type ~ ., scales = "fixed")

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugan unexpected problem or unintended behavior

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions