Reputation: 13792
I've made these pie charts:
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)
Is there any way of adjusting the size of each pie chart according to the sum of size
in each zone
?
Upvotes: 1
Views: 5556
Reputation: 226057
@lukeA's suggestion is sensible but doesn't quite work:
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")
The problem here is that the bars are drawn (in rectangular coordinates) in the middle of the x-axis; we'd like them to be drawn with their x-coordinates running from 0 to the full width, but I'm not sure how to do that. The alternative would be to do a bunch of the cumulative proportion/stacking computations by hand (or at least outside ggplot2
), then use geom_rect()
...
Here's how:
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")
Upvotes: 3