在ggplot中绘制一个简单的转换漏斗

时间:2016-03-07 22:01:34

标签: r ggplot2

我有一个简单的数据框,如下所示:

df
   steps  numbers     rate
 1 clicks 332835  100.000000
 2 signup  157697  47.379933
 3  cart   29866   8.973215
 4  buys   17012   5.111241

如何绘制简单的转化渠道而不是条形图?

1 个答案:

答案 0 :(得分:8)

如果你必须做漏斗事,它只是条形图的变化:

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

enter image description here

那就是说,&#34;漏斗图表中没有真正的重点&#34; - 相同的信息可以在简单的条形图中显示,而不用大惊小怪:

# 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

enter image description here