Home > Blockchain >  How to create two stacked bar charts next to each other using ggplot. I want to recreate the below c
How to create two stacked bar charts next to each other using ggplot. I want to recreate the below c

Time:09-08

I have the below 2 dataframes:

lc2 <- structure(list(group = 1:3, sumpct = c(13, 32, 54)), class = "data.frame", row.names = c(NA, 
-3L))

note this is for the "likelihood to click" bar (see image), where "extremely/somewhat likely" is 13%, neutral is 32, and extremely/somewhat unlikely is 54)

and

le2 <- structure(list(e = 1:3, t = c(13, 38, 48)), class = "data.frame", row.names = c(NA, 
-3L))

note similarly this code above is for "likelihood to enroll" bar below.

But I want to create this:

stacked bar chart

CodePudding user response:

lc2 <- structure(list(group = 1:3, sumpct = c(13, 32, 54)), 
                 class = "data.frame", row.names = c(NA, -3L))
le2 <- structure(list(e = 1:3, t = c(13, 38, 48)), 
                 class = "data.frame", row.names = c(NA, -3L))



lc2$type <- "click"
le2$type <- "enroll"

colnames(lc2) <- c("group", "pct", "type")
colnames(le2) <- c("group", "pct", "type")

library(data.table)
library(ggplot2)
dt <- rbindlist(list(lc2, le2))
dt[, group := as.factor(group)]
ggplot(dt, aes(x = type, y = pct, fill = group))   
  geom_bar(stat = "identity")  
  geom_text(aes(label=scales::percent(pct/100)), position = position_stack(vjust = .5)) 
  theme_classic()  
  coord_flip()
  

staked bar chart with percentage

  • Related