Feng Tian
Feng Tian

Reputation: 1589

How to keep 0 value in ggplot2 pie chart?

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?

Upvotes: 1

Views: 650

Answers (1)

Ben Bolker
Ben Bolker

Reputation: 226587

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

Upvotes: 2

Related Questions