如何创建每个面加起来为 100% 的分面饼图?

问题描述 投票:0回答:1

我想为数据集中的两个网络制作一个多面饼图,以显示每个网络中使用的网络类型(2g、3g、4g)的百分比。然而,当我尝试这样做时,两个方面/网络的百分比加起来都是 100%。如何创建一个多面饼图,其中每个单独面的百分比总计为 100%?感谢所有帮助。

image of what I have so far

这是我使用的脚本:

bigfi %>%
  drop_na(net) %>%
  filter(grepl("2015", date), net != "") %>%
  ggplot(aes(x="", fill = net)) +
  geom_bar(position="fill", color = "white") +
  facet_wrap(~network) +
  coord_polar(theta="y", start = 0) +
  theme_void() +
  geom_text(aes(label = after_stat(
    percent(ave(count, x, FUN = function(x) x / sum(x))))), 
    stat="count", position = "fill", color = "white", size=4) +
  labs(title = "Net Type Usage 2015") + 
  theme(plot.title = element_text(hjust = 0.5, face = "bold", size=4))

我正在使用 BigQuery 的数据集,表 ID:bigquery-public-data.catalonian_mobile_coverage_eu.mobile_data_2015_2017。 这是一个示例:

+   select(network, net, date)
     network net       date
1   Vodafone  3G 2015-01-05
2   Vodafone  3G 2015-01-05
3   Vodafone  3G 2015-01-05
4   Vodafone  3G 2015-01-05
5   Vodafone  3G 2015-01-05
6   Vodafone  3G 2015-01-05
7   Vodafone  3G 2015-01-05
8   Vodafone  3G 2015-01-05
9   Vodafone  3G 2015-01-05
10  Vodafone  3G 2015-01-05```
r ggplot2 pie-chart percentage
1个回答
0
投票

在计算百分比份额时,您必须考虑分面变量,即在

after_stat()
内将
PANEL
添加到
ave()
作为第二个分组变量。

使用基于

mtcars
的最小可重现示例:

library(ggplot2)
library(dplyr, warn = FALSE)
library(tidyr)
library(scales)

bigfi <- mtcars |>
  mutate(
    across(c(cyl, am), factor),
    date = 2015,
  ) |>
  select(net = cyl, network = am, date)

bigfi %>%
  drop_na(net) %>%
  filter(grepl("2015", date), net != "") %>%
  ggplot(aes(x = "", fill = net)) +
  geom_bar(position = "fill", color = "white") +
  facet_wrap(~network) +
  coord_polar(theta = "y", start = 0) +
  theme_void() +
  geom_text(
    aes(label = after_stat(
      percent(ave(count, x, PANEL, FUN = function(x) x / sum(x)))
    )),
    stat = "count", position = position_fill(vjust = .5),
    color = "white", size = 4
  ) +
  labs(title = "Net Type Usage 2015") +
  theme(
    plot.title = element_text(hjust = 0.5, face = "bold", size = 4)
  )

© www.soinside.com 2019 - 2024. All rights reserved.