调整饼图的大小

时间:2015-01-04 21:42:49

标签: r charts ggplot2

我制作了这些饼图:

df <- expand.grid(log.var = c(TRUE, FALSE), zone = 1:4)
df$proportion <- c(0.3, 0.7, 0.4, 0.6, 0.2, 0.8, 0.5, 0.5)
df$size = sample(1:20, 8)

library(ggplot2)
ggplot(df, aes(factor(1), proportion, fill = log.var)) + 
   geom_bar(stat = "identity") + coord_polar(theta = "y") + facet_grid(.~zone)

enter image description here

有没有办法根据每个sizezone的总和来调整每个饼图的大小?

1 个答案:

答案 0 :(得分:3)

@ lukeA的建议是明智的,但不太有效:

library("ggplot2"); theme_set(theme_bw())
library("dplyr")  ## for mutate()
set.seed(101)
df <- expand.grid(log.var = c(TRUE, FALSE), zone = 1:4)
df <- mutate(df,
   proportion=c(0.3, 0.7, 0.4, 0.6, 0.2, 0.8, 0.5, 0.5),
   size = sample(1:20, 8),
   totsize=ave(size, zone,FUN=sum))

g0 <- ggplot(df, aes(x=factor(1), y=proportion, fill = log.var))
g0 + geom_bar(stat="identity",aes(width=totsize))+facet_grid(.~zone)+
        coord_polar(theta = "y")

enter image description here

这里的问题是在x轴的中间中绘制条形(以直角坐标);我们希望它们用从0到全宽的x坐标绘制,但我不知道该怎么做。另一种方法是手工完成一堆累积比例/堆叠计算(或至少在ggplot2之外),然后使用geom_rect() ......

以下是:

df <- df %>% group_by(zone) %>%
    mutate(cp1=c(0,head(cumsum(proportion),-1)),
              cp2=cumsum(proportion))

ggplot(df) + geom_rect(aes(xmin=0,xmax=totsize,ymin=cp1,ymax=cp2,
                           fill=log.var)) + facet_grid(.~zone)+
                               coord_polar(theta = "y")

enter image description here