2015-01-04 75 views
1

我做了這些餅狀圖的大小:調整餅圖

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

是否有調整根據size每個zone總和每個餅圖的大小的方法嗎?

+0

像'ggplot(transform(df,sum = with(df,ave(size,zone,FUN = sum))),aes(factor(1),proportion,fill = log.var,width = sum))+ ... '? – lukeA

回答

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