1

I have 4 elements: x1 x2 x3 x4 and corresponding values:

overlap_cha <- data.frame( type=rep(c("x1","x2","x3","x4"),c(18,0,91,3)) )

When I plot pie chart, the x2 with 0 value will not be shown in the legend.

pie <- ggplot(overlap_cha, aes(x = 0, fill = type)) + geom_bar(width = 1)
pie + coord_polar(theta = "y")

How can I keep it?

Feng Tian
  • 1,559
  • 1
  • 18
  • 27

1 Answers1

2

This is similar (but maybe not completely identical to?) ggplot2 keep unused levels barplot ...

Set up data:

overlap_cha <- data.frame( type=rep(c("x1","x2","x3","x4"),c(18,0,91,3)) )

Make sure the variable has appropriate factor levels:

 overlap_cha$type <- factor(overlap_cha$type,levels=c("x1","x2","x3","x4"))


 library(ggplot2)
 pie <- ggplot(overlap_cha, aes(x = 0, fill = type)) + geom_bar(width = 1)
 pie2 <- pie + scale_fill_discrete(drop=FALSE)+scale_x_discrete(drop=FALSE)+
         coord_polar(theta = "y")

If you want to change the colours, use scale_fill_brewer (or you could use scale_fill_manual with the values argument):

 pie3 <- pie +
     scale_fill_brewer(palette="Set1",drop=FALSE)+
     scale_x_discrete(drop=FALSE)+
         coord_polar(theta = "y")

enter image description here

Community
  • 1
  • 1
Ben Bolker
  • 211,554
  • 25
  • 370
  • 453
  • Actually the `scale_fill_brewer` or `scale_fill_manual` does not work. – Feng Tian Jul 11 '16 at 14:57
  • really? what about my example, which uses `scale_fill_brewer` and seems to work ... ? – Ben Bolker Jul 11 '16 at 15:05
  • `Error in f(..., self = self) : attempt to apply non-function`. What happend? `pie <- ggplot(overlap_cha, aes(x = "", fill = Type)) + geom_bar(width = 1) + scale_fill_discrete(palette="Set1",drop=FALSE,labels = nwLabel) + scale_x_discrete(drop=FALSE)` – Feng Tian Jul 11 '16 at 15:36
  • In that example (i.e. to use `palette="Set1"`) you should use `scale_fill_brewer`, not `scale_fill_discrete` – Ben Bolker Jul 11 '16 at 15:54