繁体   English   中英

如何在 R ggplot2 中制作带有条形的漏斗图?

[英]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

我的代码看起来像这样,但我不知道如何在条形之间填充浅蓝色。 (也许有多边形?)

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

我需要相同的但没有找到,所以我创建了一个 function 来这样做。 它可能需要一些改进,但运行良好。 下面的示例仅显示数字,但您也可以添加文本。


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

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

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

在此处输入图像描述

这应该只是一个评论,因为您明确要求提供ggplot解决方案,但事实并非如此 - 我纯粹出于代码格式化的原因将其发布为答案。

您可以考虑plotly ,它具有漏斗类型。 就像是

library(plotly)
dat %>%  mutate(steps=factor(steps, unique(steps)),
    rate=sprintf("%.2f%%", rate)) %>% 
plot_ly(
    type = "funnel",
    y = ~steps,
    text= ~rate,
    x = ~numbers)

可以让你开始; 我并没有真正掌握数据中的填充,所以这可能不是你想要的。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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