How to make funnel chart with bars in R ggplot2?

I want to make a funnel chart in R with ggplot2 as following: https://chartio.com/assets/c15a30/tutorials/charts/funnel-charts/c7cd4465bc714689646515692b6dbe7c74ae7550a265cd2d6a530f1f34d68ae1/funnel-chart-example.png

My code looks like this, but I don't know how to do the the light blue fills between the bars. (maybe with polygon?)

library(ggplot2)
library(reshape2) # for melt()
library(dplyr)
# get data
dat <- read.table(text=
"steps  numbers     rate
clicks 332835  100.000000
signup  157697  47.379933
cart   29866   8.973215
buys   17012   5.111241", 
                  header = T)

barWidth <- 0.9

# add spacing, melt, sort
total <- subset(dat, rate==100)$numbers
dat$padding <- (total - dat$numbers) / 2
molten <- melt(dat[, -3], id.var='steps')
molten <- molten[order(molten$variable, decreasing = T), ]
molten$steps <- factor(molten$steps, levels = rev(dat$steps))

ggplot(molten, aes(x=steps)) +
  geom_bar(aes(y = value, fill = variable),
           stat='identity', position='stack') +
  geom_text(data=dat, 
            aes(y=total/2, label= paste(round(rate), '%')),
            color='white') +
  scale_fill_manual(values = c('grey40', NA) ) +
  coord_flip() +
  theme(legend.position = 'none') +
  labs(x='steps', y='volume')

Solution 1:

I needed the same but hadn't found one, so I created a function to do so. It might need some improvements, but it is working well. The example below shows only numbers, but you can also add texts.


x <- c(86307,
       34494,
       28127,
       17796,
       12488,
       11233
)

source("https://gist.github.com/jjesusfilho/fd14b58becab4924befef5be239c6011")

gg_funnel(x, color = viridisLite::plasma(6))

enter image description here