2
votes

My question relates to plots in ggplot. Running the code below each image should work if you load the "diamonds" dataset that comes with ggplot2.

I am trying to generate a graph like this:

Barplot of colors faceted by cut

library(ggplot2)

#First plot
p1 <- ggplot(diamonds, aes(color)) + geom_bar(aes(group = cut, y = ..density..))
p1 <- p1 + facet_wrap(~cut)
p1

but I want to color each bar in each facet by factor, like in this plot:

Color example

#Second plot
p2 <- ggplot(diamonds, aes(color)) + geom_bar(aes( y = ..density.., fill = color)) 
p2 <- p2 + facet_wrap(~cut)
p2

The problem is that "group =" and "fill=" appear to interfere with each other when I attempt to call them both; ggplot seems to ignore the "fill" command when "group" is also called.

The call to group is important because it forces the y-axis to scale for each facet, so that densities within each facet add up to 1. However, I'd like to be able to visually distinguish between groups easily using fill colors.

How can I work around this?

1

1 Answers

2
votes

The problem is with ..density... It often is a convenient shortcut, but in a more complicated situation like this one it's often easier just to calculate on your own:

library(dplyr)
diam2 <- diamonds %>% group_by(cut) %>% 
    mutate(ncut = n()) %>%
    group_by(cut, color) %>%
    summarize(den = n() / first(ncut))

ggplot(diam2, aes(x = color, fill = color, y = den)) +
    geom_bar(stat = "identity") +
    facet_wrap(~ cut)

I should add, comparing my plot with your p1, the shapes are the same but the scale looks a little different (mine being a little lower overall). I'm not sure why.