Home > Blockchain >  ggplot barplot given percentage by group
ggplot barplot given percentage by group

Time:11-13

I'm trying to build a barplot already given the percentage. I think it's a basic question, but I'm not able to find anything on the internet. The data that I have is this:

Data I'm working with

The plot that I'm trying to print would be something like this: Plot I'm trying to achive

The bars would need to reach 100% for every set of bars (that means for every year), given overRetail and belowRetail. I don't have any code to show: the closest I have been has been by not calculating the percetage, but using the absolute values. I wonder: is really a barplot what I'm looking for? Maybe other kind of plot would better fit what I'm trying to show. Thanks in advance!

CodePudding user response:

The plot you aim to make might be easier with reshaped data. Instead of one row per year, consider having one row per year and below/over.

# Setup Data
require(tidyverse)

releaseDate <- 2014:2021
belowRetail <- c(24.20635, 25.09804, 35.63403, 31.06996, 27.76025, 28.59097, 31.00559, 30.89888)
overRetail <- c(75.79365, 74.90196, 64.36597, 68.93004, 72.23975, 71.40903, 68.99441, 69.10112)
retail <- tibble(releaseDate = releaseDate, belowRetail = belowRetail, overRetail = overRetail)

You can use pivot_longer from dplyr to reshape the data.

retail <- pivot_longer(data = retail, cols = -releaseDate, names_to = "name") 

Then, you can use geom_bar, specifying name in the aesthetics (aes). Also note that it is necessary to add position = "fill" and stat = "identity". The first option makes all bars 100% and the second option uses the value of the data rather than defaulting to counts.

ggplot(data = retail)  
  geom_bar(aes(x = releaseDate, y = value, fill = name), position = "fill", stat = "identity")

Here is what it looks like.

Here is a useful source that you might want to consult.

  • Related