【问题标题】:Stacked bar chart堆积条形图
【发布时间】:2014-02-09 18:06:16
【问题描述】:

我想使用 ggplot2 和 geom_bar 创建一个堆积图。

这是我的源数据:

Rank F1     F2     F3
1    500    250    50
2    400    100    30
3    300    155    100
4    200    90     10

我想要一个堆积图,其中 x 是排名,y 是 F1、F2、F3 中的值。

# Getting Source Data
  sample.data <- read.csv('sample.data.csv')

# Plot Chart
  c <- ggplot(sample.data, aes(x = sample.data$Rank, y = sample.data$F1))
  c + geom_bar(stat = "identity")

这是我所能得到的。我不确定如何堆叠其余的字段值。

也许我的 data.frame 格式不正确?

【问题讨论】:

  • 每天都会问这个问题
  • @user2209016 查看文档:docs.ggplot2.org/current/geom_bar.html。它回答了很多常见问题。
  • 在我看来,上面文档的链接是开始学习 ggplot 的一个糟糕的地方。例如,知道“美学映射......如果您要覆盖绘图默认值,则只需要在图层级别设置”对初学者没有用处。我发现食谱网页更易于访问。

标签: r ggplot2 geom-bar


【解决方案1】:

以 Roland 的回答为基础,使用 tidyr 将数据从宽变长:

library(tidyr)
library(ggplot2)

df <- read.table(text="Rank F1     F2     F3
1    500    250    50
2    400    100    30
3    300    155    100
4    200    90     10", header=TRUE)

df %>% 
  gather(variable, value, F1:F3) %>% 
  ggplot(aes(x = Rank, y = value, fill = variable)) + 
  geom_bar(stat = "identity")

【讨论】:

    【解决方案2】:

    你需要melt你的数据框才能把它变成所谓的长格式:

    require(reshape2)
    sample.data.M <- melt(sample.data)
    

    现在您的字段值由它们自己的行表示,并通过变量列进行标识。现在可以在 ggplot 美学中利用这一点:

    require(ggplot2)
    c <- ggplot(sample.data.M, aes(x = Rank, y = value, fill = variable))
    c + geom_bar(stat = "identity")
    

    您可能还对使用构面显示多个图感兴趣,而不是堆叠:

    c <- ggplot(sample.data.M, aes(x = Rank, y = value))
    c + facet_wrap(~ variable) + geom_bar(stat = "identity")
    

    【讨论】:

      【解决方案3】:

      你说:

      也许我的 data.frame 格式不正确?

      是的,这是真的。您的数据采用 wide 格式 您需要将其放入 long 格式。一般来说,长格式更适合变量比较

      例如,使用reshape2,您可以使用melt

      dat.m <- melt(dat,id.vars = "Rank") ## just melt(dat) should work
      

      然后你得到你的条形图:

      ggplot(dat.m, aes(x = Rank, y = value,fill=variable)) +
          geom_bar(stat='identity')
      

      但使用latticebarchart 智能公式表示法,您不需要重塑数据,只需这样做:

      barchart(F1+F2+F3~Rank,data=dat)
      

      【讨论】:

      • 谢谢,这对所有其他答案都有帮助。一般来说,你喜欢在 ggplot2 上使用 lattice 吗?
      • 好问题。简而言之,ggeplot2 aes 是无与伦比的(将数据绑定到绘图功能),但有时我发现 lattice panel 非常有用,并且与 grid 包集成比 ggplot2 更容易
      • @CMichael 不。OP 大约是ggplot2,所以所有答案都指向ggplot2 而不是lattice 是正常的。但我承认关于ggplot2的问题比``lattice`更多
      【解决方案4】:

      您需要将数据转换为长格式,并且不应在aes 中使用$

      DF <- read.table(text="Rank F1     F2     F3
      1    500    250    50
      2    400    100    30
      3    300    155    100
      4    200    90     10", header=TRUE)
      
      library(reshape2)
      DF1 <- melt(DF, id.var="Rank")
      
      library(ggplot2)
      ggplot(DF1, aes(x = Rank, y = value, fill = variable)) + 
        geom_bar(stat = "identity")
      

      【讨论】: