将单个组件作为堆积条形图中的子集

时间:2014-09-05 20:05:01

标签: r plot ggplot2 bar-chart

我正在尝试创建一个堆积条形图,它将显示公司的收入和销售成本的各个组成部分(运营费用,其他固定成本等)。现在,我希望将销售成本的各个组成部分显示在收入栏之上,以便明确收入的哪一部分是销售成本。

现在,我只能创建一个叠加的条形图,它将所有内容放在一起。换句话说,销售成本会显示在收入之上。

理想情况下,我希望将销售成本的各个组成部分显示为收入的子集。 以下是我所拥有的molten数据框的简要介绍:

Time    variable    value
2013-01-01  A   84.32153
2013-02-01  A   91.41203
2013-01-01  B   1214.29960
2013-02-01  B   1224.21256
2013-01-01  C   312.78462
2013-02-01  C   175.58130
2013-01-01  D   321.12000
2013-02-01  D   298.82000

在上面的场景中,我希望B显示为超级集,A,C和D应该是上面两个月B的组成部分。

我使用以下代码:

stackbar <- ggplot(temp, aes_string(x = 'Time',y='value', fill = "variable")) +
  geom_bar(stat='identity') +
  ylab("Count") + theme(legend.title = element_blank()) +
  theme(legend.direction = "horizontal") + 
  theme(legend.position = c(1, 1)) + 
  theme(legend.justification = c(1, 0)) +
  theme(panel.grid.minor.x=element_blank(),
        panel.grid.minor.y=element_blank(), panel.background=element_blank(),
        panel.grid.major.x=element_line(color='grey90',linetype='dashed'),
        panel.grid.major.y=element_line(color='grey90',linetype='dashed')) + 
  theme(axis.ticks.x=element_blank()) + theme(axis.ticks.y=element_blank()) +
  scale_colour_discrete(limits = levels(temp$variable))

非常感谢这方面的任何帮助。

1 个答案:

答案 0 :(得分:1)

您要做的是对数据进行分组,并拥有两个geom_bar图层。首先,您想要使用变量B绘制条形图。然后,在第二个geom_bar()中绘制其余部分。我希望这会给你你想要的数字。

stackbar <- ggplot(mydf, aes(x = Time, y = value, fill = variable)) +
  geom_bar(data = mydf[mydf$variable == "B",], stat = "identity") +
  geom_bar(data = mydf[!mydf$variable == "B",], stat = "identity")+
  ylab("Count") +
  theme(legend.title = element_blank()) +
  theme(legend.direction = "horizontal") + 
  theme(legend.position = c(1, 1)) + 
  theme(legend.justification = c(1, 0)) +
  theme(panel.grid.minor.x=element_blank(),
        panel.grid.minor.y=element_blank(), panel.background=element_blank(),
        panel.grid.major.x=element_line(color='grey90',linetype='dashed'),
        panel.grid.major.y=element_line(color='grey90',linetype='dashed')) + 
  theme(axis.ticks.x=element_blank()) + theme(axis.ticks.y=element_blank()) +
  scale_colour_discrete(limits = levels(mydf$variable))

  stackbar

enter image description here