ggplot的多面形状图 [英] faceted piechart with ggplot

查看:111
本文介绍了ggplot的多面形状图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下data.frame:

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创建了一个多面条形图。

and I have created a faceted bar chart with ggplot2.

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

但是,我想要一个饼图来显示分数值(基于每个类别)。图表应该显示每个类别的饼图和每个饼图中的两个分数,每个值分别对应一个饼图。真实数据最多有6个类别,我有几个1000个数据集)。有没有一种通用的方式来做到这一点?

However, I would like to have a pie chart that shows the fraction values (based on the totals for each category). The diagram should then show one pie chart for each category and two fractions inside each pie chart, one for each value factor. The real data has up to 6 categories and I have a few 1000 data sets). Is there a generic way to do that?

推荐答案

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

One way is to calculate the percentage/ratio beforehand and then use it to get the position of the text label. See also 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))

这篇关于ggplot的多面形状图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆