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

问题描述 投票:0回答:1

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

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个回答
3
投票

也许是这样的?

library(ggplot2)

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

enter image description here

如果我们想在图中包含值,我们可以使用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))

enter image description here

最后,如果我们想在Rondenummer之后改变coord_flip()的顺序,我们可以添加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))) 

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.