在R中获取堆积区域图 [英] Getting a stacked area plot in R

查看:276
本文介绍了在R中获取堆积区域图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这个问题是前面的 question 我问。



现在我有一个案例,其中还有一个带有Prop的类别列,因此数据集变得像

 小时分类Prop2 

00 A 25
00 B 59
00 A 55
00 C 5
00 B 50
...
01 C 56
01 B 45
01 A 56
01 B 35
...
23 D 58
23 A 52
23 B 50
23 B 35
23 B 15

在这种情况下,我需要在R中用这些不同类别的百分比在每天中制作一个堆积区域图。所以,结果会如此。

  ABCD 
00 20%30%35%15%
01 25%10%40%25%
02 20%40%10%30%



20
21
22 25%10%30%35%
23 35%20%20%25%

现在我会在每个小时内获得每个类别的份额,然后绘制这个堆积区域图,其中x轴是小时和y-轴为不同颜色给出的每个类别的Prop2的百分比

ggplot2 包作为解决方案。

  R>库(ggplot2)

一个示例数据集:

  R>数据帧(t = rep(0:23,每个= 4),var = rep(LETTERS [1:4],4),val = round(runif(4 * 24,0,50)) )
R> (d,10)
t var val
1 0 A 1
2 0 B 45
3 0 C 6
4 0 D 14
5 1 A 35
6 1 B 21
7 1 C 13
8 1 D 22
9 2 A 20
10 2 B 44

$ b

然后你可以用 ggplot geom_area code>:

  R> ggplot(d,aes(x = t,y = val,group = var,fill = var))+ geom_area(position =fill)


This question is a continuation of the previous question I asked.

Now I have a case where there is also a category column with Prop. So, the dataset becomes like

Hour  Category        Prop2

00     A            25
00     B            59
00     A            55
00     C            5
00     B            50
...
01     C            56
01     B            45
01     A            56
01     B            35
...
23     D            58
23     A            52
23     B            50
23     B            35
23     B            15

In this case I need to make a stacked area plot in R with the percentages of these different categories for each day. So, the result will be like.

        A         B       C        D
00     20%       30%     35%       15% 
01     25%       10%     40%       25%
02     20%       40%     10%       30% 
.
.
.
20 
21
22     25%       10%     30%       35%
23     35%       20%     20%       25%

So now I would get the share of each Category in each hour and then plot this is a stacked area plot like this where the x-axis is the hour and y-axis the percentage of Prop2 for each category given by the different colours

解决方案

You can use the ggplot2 package from Hadley Wickham for that.

R> library(ggplot2)

An example data set :

R> d <- data.frame(t=rep(0:23,each=4),var=rep(LETTERS[1:4],4),val=round(runif(4*24,0,50)))
R> head(d,10)
   t var val
1  0   A   1
2  0   B  45
3  0   C   6
4  0   D  14
5  1   A  35
6  1   B  21
7  1   C  13
8  1   D  22
9  2   A  20
10 2   B  44

And then you can use ggplot with geom_area :

R> ggplot(d, aes(x=t,y=val,group=var,fill=var)) + geom_area(position="fill")

这篇关于在R中获取堆积区域图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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