使用ggplot绘制分面饼图

5

I have the following 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个回答

7

一种方法是事先计算百分比/比率,然后使用它来获取文本标签的位置。 另请参见当 geom_text 不适用时如何在 ggplot 中放置百分比标签?

# 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


对我来说无法运行:找不到m2,你是指m1吗?此外,在您的ddply语句中找不到变量category。 - RalfB
1
@jakub 我认为问题仍然存在。请使用以下数据框尝试您的代码:x = data.frame(category=c(1,1,1,1,2,2,2,2), value=c(2,2,1,1,2,2,2,1)) - Sandy Muspratt
啊!今天我真的很分心 :) 错误在于ddply语句中使用了错误的变量,这种情况下应该是“category”,而不是“value”...希望现在它可以以通用的方式工作... - jakub

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接