0
votes

I want to give colors to the piechart. I used scale_fill_manual(values = c("orange", "red","blue", "yellow", "green")). I want to give red color for apple, orange color for orange and blue color for grape etc. But my pie chart looks different.

d1 <- data.frame(
  labels = c("orange","apple","grape","pineapple","muskmelon"),
  value = c(1632,29,1491,1991,29)
)
d1$pos <- cumsum(d1$value) - 0.5*d1$value  

p1 <-ggplot(d1, aes(x="", y = value, fill = labels))
p1 <- p1 + geom_bar(stat="identity", width=1) 
p1 <- p1 + ggtitle("fruits")
p1 <- p1 + panel_border()
p1 <- p1 + coord_polar(theta = "y")
p1 <- p1 + xlab("")
p1 <- p1 + ylab("")
p1 <- p1 + geom_text(aes(x="", y=pos,label=labels), size=10)
p1 <- p1 + scale_fill_manual(values = c("orange", "red","blue", "yellow", "green"))
p1 <- p1 + theme(legend.position="none", 
  legend.title=element_blank(),
  axis.line=element_blank(),axis.text.x=element_blank(),
  axis.ticks=element_blank(),
  plot.title = element_text(lineheight=3, face="bold", color="black", size=25))
2

2 Answers

2
votes

This may be a little too late. I understand that the package in question here is ggplot2 but just to share how I would do it using the built-in pie function. First, I would assign the colour names to correspond each label in the data frame:

d1$colours <- c("orange", "red", "blue", "yellow", "green")

such that my d1 looks like this:

    labels value    pos colours
    orange  1632  816.0  orange
     apple    29 1646.5     red
     grape  1491 2406.5    blue
 pineapple  1991 4147.5  yellow
 muskmelon    29 5157.5   green

Then, plot using the pie function:

pie(x = d1$value, labels = d1$labels, col = d1$colours)

enter image description here

1
votes

From help(scale_fill_manual), you can pass a named vector to the values parameter:

p1 + scale_fill_manual(values = c("orange" = "orange",
                                  "apple" = "red",
                                  "grape" = "blue",
                                  "pineapple" = "yellow",
                                  "muskmelon" = "green"))