如何对大量数据进行子集或汇总,以便可以制作单独的饼图 [英] How to subset or aggregate large amounts of data so I can make separate pie charts
问题描述
我的数据如下:
Trip_Set sex
119_4 hembra
119_4 hembra
119_7 hembra
161_7 macho
193_8 hembra
255_7 macho
271_6 hembra
271_6 macho
271_6 hembra
328_7 hembra
403_3 hembra
428_2 hembra
655_4 hembra
如您所见,每个Trip_Set都有许多男性或女性(有些人只有一个).我希望为每组旅行制作一个单独的饼图,以显示每种旅行的男女比例.这只是我的数据集的一小段(真正的数据集比数百个Trip_Set大得多).
As you can see, each Trip_Set has a number of males or females (some just have one). I wish to make a separate pie chart for each trip set to show the ratio of males to females for each. This is just a snippet of my dataset (the real one is much larger with hundreds of Trip_Sets).
我的饼图代码是这样的:
My code for the pie chart is this:
data = dframe2
data = dframe2
library(ggplot2)
pie <- ggplot(dframe2, aes(x=1, y=Trip_Set, fill=sex)) +
geom_bar(stat="identity") +
ggtitle("Sex ratio per line")
pie <- pie + coord_polar(theta='y')
print(pie)
但是,这只是绘制了上面显示的所有数据的饼图-我希望能够为每个Trip_Set制作一个饼图.我设法通过创建一个子集然后使用以下代码运行饼图代码来手动完成此操作:
However, this just plots a pie chart of all of the data shown above- I wish to be able to make one pie chart for each Trip_Set. I have managed to do this manually by creating a subset and then running the piechart code using the code below:
Trip119_4<-subset(dframe2,Trip_Set=='119_4')
pie <- ggplot(Trip119_4, aes(x=1, y=Trip_Set, fill=sex)) +
geom_bar(stat="identity") +
ggtitle("Sex ratio per line")
pie <- pie + coord_polar(theta='y')
print(pie)
有没有一种方法可以为每个Trip_Set制作单独的饼图,而不必键入并重命名数百个重复的子集?有人提到聚合函数,但是对于我一生来说,我无法使其正常工作.
Is there a way I can do separate pie charts for each Trip_Set, without having to type in and rename hundreds of repeated subsets? Someone mentioned an aggregate function but for the life of me I cannot get it to work.
推荐答案
您可能需要研究facet_wrap
-如果我正确理解了这个问题,我认为以下是最有效的方法:
You may want to look into facet_wrap
-- I think the following is the most effective if I understand the question correctly:
ggplot(data=df, aes(x=sex, fill=sex)) +
geom_bar(stat="bin") +
facet_wrap(~ Trip_Set)
您也可以这样构造它:
ggplot(data=df, aes(x=Trip_Set, fill=sex)) +
geom_bar(stat="bin")
这篇关于如何对大量数据进行子集或汇总,以便可以制作单独的饼图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!