使用ggplot2制作堆积区域图

时间:2011-01-10 20:56:28

标签: r ggplot2

我正在使用以下数据结构来尝试制作堆积区域图表:

df <- data.frame(PopDen = c( 0.002279892, 0.002885407, 0.004291351, 0.002457731, 0.006631572, 0.007578882, 0.004465446, 0.007436628, 0.009001456, 0.006951703, 0.003602076, 0.005695585, 0.005819783, 0.007412274, 0.004931548, 0.006257411, 0.008635908, 0.005438558, 0.002251421,0.006438558), DomArea = c( 253500, 135270, 197180, 131590, 142210, 166920, 125640, 184600, 139940, 126280, 127760, 190940, 133440, 143510, 117260, 69340, 143620, 127480, 181970,164180), PR_Cat = c( "High", "High", "Low", "Low", "Low", "Low", "Low", "Low", "High", "High", "Medium", "Medium", "Medium", "Low", "Low", "Medium", "Medium", "Low", "Low","Low") )

p <- ggplot(df, aes(PopDen, order(DomArea), colour = PR_Cat))  
p + geom_area(aes(colour = PR_Cat, fill= PR_Cat), position = 'stack')

但是,我不明白如何将这些区域叠加在一起;目前他们正在重叠。我假设我在这里需要一个position = 'stack'参数,但无论是否包含,情节看起来都是一样的。

此外,是否可以按DomArea中的某个类别订购PR_Cat,还是需要重新组织我的数据?

1 个答案:

答案 0 :(得分:23)

我不确定你在这里绘制什么,但是你不想在 y 轴上绘制PopDen而不是 x 轴?您可以使用DomArea包中的PR_Cat按每个ddply类别订购plyr,然后堆叠的工作方式如下: 的 修改 我意识到你可能希望按照Low, Medium High的顺序堆积图,所以我们需要首先在PR_Cat因子上强制执行这个排序:

df$PR_Cat <- ordered( df$PR_Cat, levels = c('Low', 'Medium', 'High'))

现在使用DomAreaByCat创建ddply列:

df <- ddply(df, .(PR_Cat), transform, DomAreaByCat = order(DomArea))

您的df将如下所示:

> df
        PopDen DomArea PR_Cat DomAreaByCat
1  0.004291351  197180    Low            8
2  0.002457731  131590    Low            5
3  0.006631572  142210    Low            9
4  0.007578882  166920    Low            2
5  0.004465446  125640    Low            3
6  0.007436628  184600    Low            7
7  0.007412274  143510    Low           11
8  0.004931548  117260    Low            4
9  0.005438558  127480    Low           10
10 0.002251421  181970    Low            6
11 0.006438558  164180    Low            1
12 0.003602076  127760 Medium            4
13 0.005695585  190940 Medium            1
14 0.005819783  133440 Medium            3
15 0.006257411   69340 Medium            5
16 0.008635908  143620 Medium            2
17 0.002279892  253500   High            4
18 0.002885407  135270   High            2
19 0.009001456  139940   High            3
20 0.006951703  126280   High            1

然后你可以像这样做堆积区域图:

p <- ggplot(df, aes( DomAreaByCat, PopDen))

p + geom_area(aes(colour = PR_Cat, fill= PR_Cat), position = 'stack')   

alt text