【问题标题】:How to make a stacked barchart in ggplot from a long dataframe format?如何从长数据框格式在 ggplot 中制作堆叠条形图?
【发布时间】:2019-03-28 11:40:51
【问题描述】:

我有一个长数据框格式,它是这样创建的:

testAppVectorJG <- c(17, 155, 200, 200, 382, 499, 548, 548, 642, 642, 699, 699)
testVectorJG <- c(testAppVectorJG[1], diff(testAppVectorJG))

testAppVectorJW <- c(145, 209, 366, 548, 548, 613, 746, 928, 1064, 1266, 1371, 1573)
testVectorJW <- c(testAppVectorJW[1], diff(testAppVectorJW))

test_df <- data.frame(puntenvector = c(testVectorJG, testVectorJW),
                      team = c(rep("Jasper & Gijs", length(testAppVectorJG)),
                               rep("Jaap & Wil", length(testAppVectorJW))),
                      Rondenummer = as.factor(1:length(testVectorJG)))

我想制作一个堆叠条形图,每个“Rondenummer”(即已玩的回合数)都有一个条形图。我想查看每支球队每轮得分的百分比/分布。

到目前为止我已经尝试过:

ggplot(data = test_df, aes(Rondenummer)) +
    geom_bar(aes(x = puntenvector, fill = team))

然后我得到:

Warning message:
position_stack requires non-overlapping x intervals

根本不是我想要的情节。我如何实现这个相当简单的情节?

【问题讨论】:

    标签: r ggplot2 bar-chart geom-bar stacked-chart


    【解决方案1】:

    也许是这样的?

    library(ggplot2)
    
    ggplot(data = test_df, aes(Rondenummer, puntenvector, fill = team)) +
       geom_bar(stat='identity')
    

    如果我们想在图中包含值,我们可以使用 labelgeom_text

    ggplot(data = test_df, 
          aes(Rondenummer, puntenvector, fill = team, label = puntenvector)) +
          geom_bar(stat='identity') +
          geom_text(position = position_stack(vjust = 0.5))
    

    最后,如果我们想在coord_flip() 之后反转Rondenummer 的顺序,我们可以添加scale_x_discrete 并反转级别。

     ggplot(data = test_df, 
       aes(Rondenummer, puntenvector, fill = team, label = puntenvector)) +
       geom_bar(stat='identity') +
       geom_text(position = position_stack(vjust = 0.5)) +
       coord_flip() + 
       scale_x_discrete(limits = rev(levels(test_df$Rondenummer))) 
    

    【讨论】:

    • 是的!这正是我想要的,谢谢!
    • 有什么方法可以将每个分数的值包含在条中吗?所以在第 1 轮中,蓝色显示“17”,红色显示“145”?
    • @JNab 我们可以使用geom_text。用那个更新了答案。
    • 最后一个问题;当我现在想让它水平时,我可以添加+ coord_flip(),但它会从顶部的 12 变为底部的 1。那我该如何扭转呢?
    • @JNab 从底部的 1 到顶部的 12 是自然的显示方式,但如果您需要反转它,我们可以使用 scale_x_discrete。我已经更新了答案。
    猜你喜欢
    • 2022-11-23
    • 2016-01-29
    • 2018-03-17
    • 1970-01-01
    • 1970-01-01
    • 2021-01-17
    • 2021-11-16
    • 1970-01-01
    • 2013-06-01
    相关资源
    最近更新 更多