Jason
Jason

Reputation: 1130

Reset color in each facet ggplot2 R

I have the frequency counts of three variables and want to show the frequency count in a pie chart. I tried ggplot and used the following code:

library(ggplot2)
df = data.frame(var = rep(c('a','b','c'),each = 3),
            class = letters[1:9],
            count = rep(1:3, 3))

ggplot(df, aes(x = '', y = count, fill = class)) + 
  geom_bar(width = 0.5, stat = 'identity') + 
  coord_polar('y', start = 10) + facet_wrap(~var) + 
  theme(legend.position = 'none')

I got the following graph: enter image description here

However, I want something like this:

enter image description here

How can I reset the color in each panel?

Upvotes: 3

Views: 1365

Answers (1)

Claus Wilke
Claus Wilke

Reputation: 17790

You'll have to introduce a dummy variable that is the same in each facet:

df = data.frame(var = rep(c('a','b','c'),each = 3),
                class = letters[1:9],
                dummy = rep(letters[1:3], 3),
                count = rep(1:3, 3))

ggplot(df, aes(x = '', y = count, fill = dummy)) + 
  geom_bar(width = 0.5, stat = 'identity') + 
  coord_polar('y', start = 10) + facet_wrap(~var)

enter image description here

I removed the theme(legend.position = 'none') line so the plot actually looks like the one you made.

Upvotes: 5

Related Questions