如何从长数据帧格式在ggplot中制作堆叠条形图?

How to make a stacked barchart in ggplot from a long dataframe format?

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

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'(即玩的回合数)都有一个条形图。我想查看每个团队每轮的 percentage/distribution 分。

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

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

但后来我得到:

Warning message:
position_stack requires non-overlapping x intervals

而且完全不是我想要的情节。我如何实现这个相当简单的情节?

也许是这样的?

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)))