简体   繁体   中英

How to create two stacked bar charts next to each other using ggplot. I want to recreate the below chart:

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:

堆积条形图

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

带百分比的质押条形图

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM