【问题标题】:How to plot percentages instead of counts in ggplot2 geom_col (R)?如何在 ggplot2 geom_col (R) 中绘制百分比而不是计数?
【发布时间】:2021-01-10 21:08:46
【问题描述】:

我有一个数据集,其中包含来自唯一身份用户的展示次数以及该用户是否已转化 = 1 或未转化 (=0)。我想创建一个显示 20 次展示间隔的转化率的 col 图表。这意味着对于每个时间间隔,转化率是该展示时间间隔内的转化用户数除以该时间间隔内的唯一身份用户数。

例如,对于这个数据集:

# A tibble: 19 x 2
   converted tot_impr
       <dbl>    <dbl>
 1         0       19
 2         0        4
 3         1       19
 4         0       13
 5         0       18
 6         1        9
 7         1       17
 8         1        8
 9         1        8
10         1       11
11         0        8
12         0       19
13         1        8
14         0        8
15         1       18
16         0       12
17         1        5
18         1       12
19         0        1

我应该会看到这些转化率:

我已经设法使用 ggplot2 geom_col 使用以下代码计算每个时间间隔的转换用户数:

ggplot(data = db) + 
  geom_col(mapping = aes(x = tot_impr, y = converted), width=5)

我正在努力强制 geom_col 不在 y 轴上显示转换后的计数,而是显示转换后的百分比相对于该展示间隔内单个样本总数的百分比。

有人可以帮我吗?

提前谢谢你!

【问题讨论】:

  • 您是否尝试过先计算百分比并在aes 调用中将其传递给y
  • 是的,最好先计算一下。也请参阅此处以发布您的数据集:stackoverflow.com/questions/5963269/…
  • 您的数据中的用户信息在哪里?对于 0-5 bin,您如何将 countconverted 分别设为 3 和 1?

标签: r ggplot2 tidyverse


【解决方案1】:

试试这个。最好在绘图之前计算变量:

library(dplyr)
library(ggplot2)
#Code
df %>% mutate(Cut=cut(tot_impr,breaks = seq(0,20,by=5),include.lowest = T,
                      right = T,dig.lab = 10)) %>%
  group_by(Cut) %>%
  summarise(N=n(),converted=sum(converted)) %>%
  mutate(conv_rate=converted/N) %>%
  ggplot(aes(x=Cut,y=conv_rate))+
  geom_bar(stat='identity',fill='magenta')+
  scale_y_continuous(labels = scales::percent)

输出:

使用的一些数据:

#Data
df <- structure(list(converted = c(0L, 0L, 1L, 0L, 0L, 1L, 1L, 1L, 
1L, 1L, 0L, 0L, 1L, 0L, 1L, 0L, 1L, 1L, 0L), tot_impr = c(19L, 
4L, 19L, 13L, 18L, 9L, 17L, 8L, 8L, 11L, 8L, 19L, 8L, 8L, 18L, 
12L, 5L, 12L, 1L)), row.names = c(NA, -19L), class = "data.frame")

【讨论】:

    猜你喜欢
    • 2012-07-14
    • 2019-03-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-09-06
    • 1970-01-01
    相关资源
    最近更新 更多