How to create faceted pie chart where each facet adds up to 100%?

37 Views Asked by At

I want to make a faceted pie chart for two networks in my dataset, to display the percentage of net types (2g,3g,4g) used in each network. However, when I try to do this, the percentages add up to 100% across both facets/networks. How can I create a faceted pie chart where the percentages in each individual facet totals 100%? All help is appreciated.

image of what I have so far

Here is the script I've used:

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

I am working with the dataset from BigQuery, table ID: bigquery-public-data.catalonian_mobile_coverage_eu.mobile_data_2015_2017. Here is a sample:

+   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```
1

There are 1 best solutions below

0
stefan On

You have to account for the faceting variable when computing the percentage shares, i.e. inside after_stat() add PANEL to ave() as a second grouping variable.

Using a minimal reproducible example based on 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)
  )