2

I have a long dataframe format which is created like this:

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

I want to make a stacked bar chart with a bar per 'Rondenummer' (i.e. number of the round played). I want to see the percentage/distribution of points per round per team.

So far I have tried:

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

But then I get:

Warning message:
position_stack requires non-overlapping x intervals

And not at all the plot I want. How do I achieve this fairly simple plot?

JNab
  • 135
  • 10

1 Answers1

4

Maybe something like this ?

library(ggplot2)

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

enter image description here

If we want to include the values in the plot we can use label with geom_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

And finally if we want to reverse the order of Rondenummer after coord_flip() we can add scale_x_discrete and reverse the levels.

 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

Ronak Shah
  • 377,200
  • 20
  • 156
  • 213
  • Yes! That's exactly what I was looking for, thanks! – JNab Mar 28 '19 at 12:02
  • Could there be any way to include the value of each score in the bars? So that for round 1 it displays '17' in the blue and '145' in the red? – JNab Mar 28 '19 at 12:06
  • 1
    @JNab We can use `geom_text`. Updated the answer with that. – Ronak Shah Mar 28 '19 at 12:12
  • One last question though; when I now want to make it horizontal I can add `+ coord_flip()` to it, but then it goes from 12 on the top to 1 on the bottom. How can I then reverse that? – JNab Mar 28 '19 at 16:01
  • 1
    @JNab starting from 1 at the bottom to 12 at the top is the natural way of displaying it but if you need to reverse it we can use `scale_x_discrete`. I have updated the answer. – Ronak Shah Mar 28 '19 at 17:02