ggplot2堆积条形图堆栈的顺序与源数据不同

时间:2017-02-03 23:36:22

标签: r plot ggplot2

我正在尝试使用ggplot2在R中制作堆积条形图,但是,我无法重现我在网上找到的先前示例。

样本数据:

d <- data.frame(year = factor(sample(2010:2014, 400, replace=T)), 
                continent = factor(sample(c("EU", "US", "Asia"), 400, replace=T)), 
                gender = factor(sample(c("male", "female"), 400, replace=T)), 
                amount = sample(20:5000, 400, replace=T))

ggplot代码:

ggplot(data=d, aes(x=year, y=amount, fill=gender)) + geom_bar(stat="identity")

如果根据blog post by Christoph Herzog生成以下图表而无需手动排序源数据:

Desired Results

但是,我在不应用任何订购的情况下获得的实际结果是:

Actual Results

有没有人可以向我解释为什么会这样? ggplot2是否有变化,我无法找到?我忽略了什么吗?

更新:1

我尝试使用强制订单,但没有运气:

ggplot(data=d, aes(x=year, y=amount, fill=gender, order=as.numeric(row.names(d)))) + 
  geom_bar(stat="identity")

我正在使用ggplot2_2.2.1和R版本3.3.2。

更新:2

以下代码会产生未排序的结果,但有几个问题。

  1. 情节仅限于前5000(金额),我不知道为什么。
  2. 尝试更改y轴显示&gt; 5000为空白。
  3. 条形图的布局似乎与目标图的下限5000不匹配。
  4. ggplot(data=d, aes(x=year, y=amount)) + stat_identity(geom = "bar", aes(fill=gender))
    

    Cropped, unsorted

    更新:3

    在某种程度上,可以使用以下代码获得所需的结果:

    ggplot(data=d, aes(x=year, y=amount, fill=gender, group = continent)) +
      geom_bar(stat="identity")
    

    但是,您需要对第二个参数进行分组以实现此目的这一事实并不适合我的目标应用程序。我正在寻找一个完全没有排序的图,其中只有行号决定了堆叠顺序。

    Grouped plot

1 个答案:

答案 0 :(得分:0)

根据Q的更新3,OP正在寻找一个完全未排序的图,其中只有行号决定了堆叠顺序

我相信这可以通过

来实现
ggplot(data=d, aes(x=year, y=amount, fill=gender, group=row.names(d))) + 
  geom_col()

enter image description here

OP已在其更新3中使用continent作为group美学。此处,row.names(d)返回的行号或行ID用于对数据进行分组。

geom_col()geom_bar(stat="identity")版本2.2.0引入ggplot2的快捷方式。

请注意,结果可能会有所不同,因为OP已省略set.seed()可重复创建样本数据。

相关问题