与ggplot的刻面饼图

时间:2014-03-23 15:21:05

标签: r ggplot2 pie-chart facet

我有以下data.frame:

x  = data.frame(category=c(1,1,1,1,2,2,2,2), value=c(1,2,1,1,2,2,2,1));
x$category = as.factor(x$category);
x$value = as.factor(x$value);

我用ggplot2创建了一个多面条形图。

ggplot(x, aes(value, fill=category)) + geom_bar() + facet_wrap(~category);

但是,我希望有一个饼图,显示分数值(基于每个类别的总计)。然后,该图应显示每个类别的一个饼图和每个饼图内的两个分数,每个值因子一个。真实数据最多有6个类别,我有几千个数据集。是否有通用的方法来做到这一点?

1 个答案:

答案 0 :(得分:4)

一种方法是预先计算百分比/比率,然后使用它来获取文本标签的位置。另请参阅how to put percentage label in ggplot when geom_text is not suitable?

# Your data
y  = data.frame(category=c(1,1,1,1,2,2,2,2), value=c(2,2,1,1,2,2,2,1))

# get counts and melt it
data.m = melt(table(y)) 
names(data.m)[3] = "count"

# calculate percentage:
m1 = ddply(data.m, .(category), summarize, ratio=count/sum(count))

#order data frame (needed to comply with percentage column):
m2 = data.m[order(data.m$category),]

# combine them:
mydf = data.frame(m2,ratio=m1$ratio)

# get positions of percentage labels:
mydf = ddply(mydf, .(category), transform, position = cumsum(count) - 0.5*count) 

# create bar plot
pie = ggplot(mydf, aes(x = factor(1), y = count, fill = as.factor(value))) +
  geom_bar(stat = "identity", width = 1) +
  facet_wrap(~category)

# make a pie
pie = pie + coord_polar(theta = "y")

# add labels
pie + geom_text(aes(label = sprintf("%1.2f%%", 100*ratio), y = position))

enter image description here