ggplot returning all black plots?

Percentages <- heart_filtered %>% count(Sex)%>% mutate(percentage=n/sum(n)*100)
ggplot(Percentages,aes(x= "", y= n),fill= Sex) + geom_bar(stat="identity",width = 1) + coord_polar(theta= "y")+labs(title= "Percentage Distribution of Sex ")+
theme_void() + geom_text(aes(label=paste0(round(percentage,1),"%")),position = position_stack(vjust=0.5))+ scale_fill_manual( values=c("M" = "red","F"= "green"))

I have used the above code to produce a pie chart. However, all i get is a black pie chart. Can you see why?

The fill aesthetic needs to be inside of the aes().

ggplot(Percentages,aes(x= "", y= n,fill= Sex)) + geom_bar(stat="identity",width = 1) + coord_polar(theta= "y")+labs(title= "Percentage Distribution of Sex ")+
theme_void() + geom_text(aes(label=paste0(round(percentage,1),"%")),position = position_stack(vjust=0.5))+ scale_fill_manual( values=c("M" = "red","F"= "green"))

Just a quick follow-up to @FJCC's solution to clarify the how the code you wrote is processed, Sameera.

Here, the fill argument is ignored because ggplot() can only be made aware of the Sex column if it appears within the aes() function (which is where @FJCC's suggestion comes from):

However, the fill argument can appear outside of the aes() function as long as it is assigned a vector of colors, for example like this:

  ggplot() +
  geom_bar(aes(0:1), fill = c("red","green"))

The aes() function is used to translate column data (in this case sex) into visual information (color), but if you supply the visual information directly, you don't need to place the corresponding argument inside of aes().

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.