1

我在互联网上搜索过,找不到像我这样的例子。我有如下数据:

                        Formación   En consolidación   Consolidado

Ene-Abr 2009    Meta       40          30                 30

                Realizado  35          45                 20

May-Ago 2009    Meta       35          35                 30

                Realizado   34          45                 20

Sep-Dic 2009    Meta       30          30                 40

                Realizado  20          40                 20

我需要一个堆积条形图,如下所示:

http://imageshack.us/photo/my-images/90/efk6.png/

请注意,该图有两个级别组。

4

2 回答 2

3

首先,日期栏需要填写,不能有空行,日期也要包括年份。我不知道你是如何得到你的数据的,所以在计算上做这件事可能需要一些修补,但这不应该那么难。在这种情况下,我是手动完成的:

> df
       Periodo     Grupo Formacion En.consolidacion Consolidado
1 Ene-Abr.2009      Meta        40               30          30
2 Ene-Abr.2009 Realizado        35               45          20
3 May-Ago.2009      Meta        35               35          30
4 May-Ago.2009 Realizado        34               45          20
5 Sep-Dic.2009      Meta        30               30          40
6 Sep-Dic.2009 Realizado        20               40          20

(而不是空格,我在变量名中使用了点。)之后,melt()plyr包中使用它很容易,并且facet_wrap

library(ggplot2)
library(plyr)

m=melt(df)
ggplot(m,aes(x=factor(Grupo),y=value,fill=factor(variable))) + 
  geom_bar(position="fill", stat="identity") +
  scale_y_continuous(labels  = percent, 
                     breaks=c(0.2,0.4,0.6,0.8,1)) + # you can set the breaks to whatever you want
  facet_wrap(~ Periodo)

这是你想要的吗?

在此处输入图像描述

这是您的(编辑的)数据:

df = structure(list(Periodo = structure(c(1L, 1L, 2L, 2L, 3L, 3L), .Label = c("Ene-Abr.2009", 
"May-Ago.2009", "Sep-Dic.2009"), class = "factor"), Grupo = structure(c(1L, 
2L, 1L, 2L, 1L, 2L), .Label = c("Meta", "Realizado"), class = "factor"), 
    Formacion = c(40L, 35L, 35L, 34L, 30L, 20L), En.consolidacion = c(30L, 
    45L, 35L, 45L, 30L, 40L), Consolidado = c(30L, 20L, 30L, 
    20L, 40L, 20L)), .Names = c("Periodo", "Grupo", "Formacion", 
"En.consolidacion", "Consolidado"), class = "data.frame", row.names = c(NA, 
-6L))
于 2013-08-24T08:08:36.217 回答
0

我找不到与您完全相同的示例,但我可以为您提供一些想法,这些想法可能对您有所帮助:

要对相关条进行分组,该ggplot2软件包提供了两种可能性:

  1. geom_bar(position="dodge")使用命令将两个相关条彼此相邻放置,如下所示:http: //www.cookbook-r.com/Graphs/Bar_and_line_graphs_ (ggplot2)/#bar-graphs

  2. facet_grid(...)使用(在 cookbook-r 中,您可以在 Index >> Graphs >> Facets(ggplot2) 下找到有关该标题的更多信息)将相关条分组在一个共同的标题下。

如果您决定使用ggplot2,您可能想尝试example(geom_bar),它还将为您提供一些有关如何创建堆叠图的示例(例如,使用position="fill",它将为您提供与上述类似的堆叠条形图)。

不幸的是,我不知道如何结合绘图处理像您这样复杂的数据。但是reshape每当我需要转换我的数据时,这个包对我有很大帮助,例如使用melt()函数,因为它在这里使用:http: //www.cookbook-r.com/Manipulating_data/Converting_data_between_wide_and_long_format/

希望我能帮上一点忙。随时给我一些反馈给我的答案。

马库斯

于 2013-08-22T14:04:22.587 回答