我有4个元素:x1 x2 x3 x4和相应的值:
overlap_cha <- data.frame( type=rep(c("x1","x2","x3","x4"),c(18,0,91,3)) )
当我绘制饼图时,图例中不会显示带有0值的x2
。
pie <- ggplot(overlap_cha, aes(x = 0, fill = type)) + geom_bar(width = 1)
pie + coord_polar(theta = "y")
我该如何保留它?
答案 0 :(得分:2)
这是类似的(但可能不完全相同?)ggplot2 keep unused levels barplot ...
设置数据:
overlap_cha <- data.frame( type=rep(c("x1","x2","x3","x4"),c(18,0,91,3)) )
确保变量具有适当的因子水平:
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")
如果您想更改颜色,请使用scale_fill_brewer
(或者您可以将scale_fill_manual
与values
参数一起使用):
pie3 <- pie +
scale_fill_brewer(palette="Set1",drop=FALSE)+
scale_x_discrete(drop=FALSE)+
coord_polar(theta = "y")