Plot a simple conversion funnel in ggplot

后端 未结 1 1660
野趣味
野趣味 2021-01-02 16:09

I have a simple dataframe that looks like this:

df
   steps  numbers     rate
 1 clicks 332835  100.000000
 2 signup  157697  47.379933
 3  cart   29866   8.         


        
1条回答
  •  孤街浪徒
    2021-01-02 16:41

    If you must do the funnel thing, it's just a variation on bar chart:

    library(ggplot2)
    library(reshape2) # for melt()
    
    # 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)
    
    # 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='stage', y='volume')
    

    That said, there's no real point in a "funnel chart" - the same information can be presented in a plain bar chart with less fuss:

    # 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)
    
    # order x axis
    dat$steps <- factor(dat$steps, levels = dat$steps)
    
    # plot
    ggplot(dat, aes(x=steps, y=numbers)) +
      geom_bar(stat='identity') +
      geom_text(aes(label = paste(round(rate), '%')), vjust=-0.5
    

    0 讨论(0)
提交回复
热议问题