Search code examples
rggplot2geom-bar

How do I have a filled bar plot expressing the ratio of quantities?


In RStudio, I have the following data frame:

   Month   Faves     Retweets Total
1. 2019-09 1267.0000 423.0000 1690.000
2. 2019-10 720.7819 294.8349  1015.617
3. 2019-11 741.2318 312.8748 1054.107
4. 2019-12 734.6458 314.0186 1048.664
5. 2020-01 754.9029 328.4743 1083.377
6. 2020-02 741.4250 330.2179 1071.643
7. 2020-03 809.6948 363.0484 1172.743
8. 2020-04 809.5476 354.3307 1163.878

I would like to show the ratio of likes to retweets using a stacked, filled bar plot, with one column per month, with the maximum y-value as 1 and the minimum as 0. I suspect I have to use ggplot and geom_bar with identity somehow. Any help would be greatly appreciated!


Solution

  • I think you want the following:

    library(dplyr)
    library(tidyr)
    
    df %>%
      dplyr::select(-Total) %>%
      pivot_longer(-Month) %>%
      ggplot(aes(x = Month, y = value, fill = name)) +
      geom_bar(stat='identity', position = 'fill')
    

    1