msug
msug

Reputation: 123

Create multiple pie charts with same colors

I am creating two pie charts using ggplot. One pie chart has the information of year 2000 and the other one from 2010. My data frame looks like this:

dat <- data.frame(consumer = c("A","A","A","A","A","A"),
                  producer = c("B","C","D","B","C","D"),
                  value = c(15,26,47,58,23,10),
                  year = c(2000, 2000, 2000, 2010, 2010, 2010),
                  color = c("red", "blue", "green", "red", "blue", "green"))

When using scale_fill_manual(values = dat$color), I do not get the colors according to the producer, but just some random colors of the "color" column. How can I specify the colors according to the "producer" column?

Edit: Here is the code for the plots

A_2000 <- filter(dat, year == 2000)
A2000 <- ggplot(A_2000, aes(x="", y=value, fill=producer)) +
  geom_bar(stat="identity", width=1, color="white") +
  coord_polar("y", start=0) +
  theme_void() +
  scale_fill_manual(values = dat$color)

A_2010 <- filter(dat, year == 2010)
A2010 <- ggplot(A_2010, aes(x="", y=value, fill=producer)) +
  geom_bar(stat="identity", width=1, color="white") +
  coord_polar("y", start=0) +
  theme_void() +
  scale_fill_manual(values = dat$color)

ggarrange(A2000, A2010, 
          ncol = 2, nrow = 1)

Thanks!

Upvotes: 1

Views: 652

Answers (1)

Allan Cameron
Allan Cameron

Reputation: 174468

You need to map the producer column to the fill aesthetic:

library(ggplot2)

ggplot(dat, aes(x = 1, y = value, fill = producer)) +
  geom_col(position = 'fill') +
  coord_polar(theta = 'y') +
  facet_grid(.~year) +
  scale_fill_manual(values = c(B = 'gold', C = 'tomato2', D = 'deepskyblue4')) +
  theme_void(base_size = 16)

enter image description here

Upvotes: 3

Related Questions