简体   繁体   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 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')

I needed the same but hadn't found one, so I created a function to do so.我需要相同的但没有找到,所以我创建了一个 function 来这样做。 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))

在此处输入图像描述

This should be just a comment, since you explicitly asked for a ggplot solution, which this is not - I posted it as an answer purely for reasons of code formatting.这应该只是一个评论,因为您明确要求提供ggplot解决方案,但事实并非如此 - 我纯粹出于代码格式化的原因将其发布为答案。

You could consider plotly , which has a funnel type.您可以考虑plotly ,它具有漏斗类型。 Something like就像是

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

could get you started;可以让你开始; I do not really grasp the padding you have in your data, so this might not be exactly what you want.我并没有真正掌握数据中的填充,所以这可能不是你想要的。

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

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