Home > Blockchain >  How do I create a stacked bar chart in ggplot2 with grouped y values?
How do I create a stacked bar chart in ggplot2 with grouped y values?

Time:03-18

I'm trying to create a stacked bar chart in RStudio using ggplot2. I want Year on the x-axis with stacked bars based on revenue values for Recorded Music, Music Publishing, and Live Music.

My data:

Year Recorded Music Music Publishing Live Music
2014 13.4 11.3 24.2
2015 14 10.4 25.2
2016 15.2 11.2 25.8
2017 16.6 11.5 26.7
2018 18.1 11.5 27.9
2019 19.6 12.1 28.6
2020 21.1 11.4 7.3

My code so far:

ggplot(data = Music_Rev_Data, aes(x=Year, y = ????)) 
  geom_bar(position = "stack", stat = "identity")

I don't know how to group the y variables/objects and it's driving me insane - I'm obviously new to R.

CodePudding user response:

library(tidyverse)
Music_Rev_Data %>%
  pivot_longer(-Year, names_to = "type") %>%
  ggplot(aes(Year, value, fill = type))  
  geom_col()

enter image description here

CodePudding user response:

An alternative stacked bar graph that shows the value for each category in the sample variable.

Sample code:

    library(ggplot2)
    
  df<-reshape2::melt(Music_Rev_Data, id.var = c("Year")) 
  
  df$variable=factor(df$variable, levels=c("Live.Music", "Music.Publishing", "Record.Music"))
  
  ggplot(df, aes(Year, value, fill = variable))  
  geom_col(position = position_fill())  
  scale_fill_discrete(name="Type", labels=c("Live music","Music publishing","Record music")) 
  scale_y_continuous(labels = scales::percent)  
  labs(x="Year", y="%", fill="Type") 
  geom_text(aes(label = value), position = position_fill(vjust = .5),  size=9) 
  theme_minimal() 
    theme(axis.text.x = element_text(hjust = 1, face="bold", size=12, color="black"), 
          axis.title.x = element_text(face="bold", size=16, color="black"),
          axis.text.y = element_text(face="bold", size=12, color="black"),
          axis.title.y = element_text(face="bold", size=16, color="black"),
          strip.text = element_text(size=10, face="bold"),
          plot.title = element_text(hjust = 0.5,size=20, face="bold"),
          legend.text = element_text( color = "black", size = 16,face="bold"),
          legend.position="bottom",
          legend.box = "horizontal",
          legend.title = element_blank())

Plot:

enter image description here

Sample data:

Music_Rev_Data<-structure(list(Year = c(2014, 2015, 2016, 2017, 2018, 2019, 2020
), Record.Music = c(13.4, 14, 15.2, 16.6, 18.1, 19.6, 21.1), 
    Music.Publishing = c(11.3, 10.4, 11.2, 11.5, 11.5, 12.1, 
    11.4), Live.Music = c(24.2, 25.2, 25.8, 26.7, 27.9, 28.6, 
    7.3)), class = "data.frame", row.names = c(NA, -7L))
  • Related