Bar Charts to Pie Charts: Another Look

stats
dataviz
Author

Andy Grogan-Kaylor

Published

September 9, 2023

Background

A quick look at moving from bar charts to pie charts.

A longer explanation of some issues is here: https://agrogan1.github.io/posts/bar-charts-in-ggplot2/

Get Data

Show the code
load("social-service-agency.RData")
age program gender
23 Program B Male
39 Program C Female
26 Program C Female
24 Program D Male
36 Program C Female
33 Program C Male

Call ggplot

Show the code
library(ggplot2)

One Dimension of Data (program)

Bar Chart

Show the code
ggplot(clients, # data I am using
       aes(x = program, # x is program
           fill = program)) + # fill is also program
  geom_bar() # use bars

Stacked Bar Chart

Show the code
ggplot(clients, # data I am using
       aes(x = 1, # x is now 1 for everyone
           fill = program)) + # fill is program
  geom_bar() # use bars

Pie Chart

Show the code
ggplot(clients, # data I am using
       aes(x = 1, # x is now 1 for everyone
           fill = program)) + # fill is program
  geom_bar() + # use bars
  coord_polar(theta = "y") + # use polar coordinates
  theme_void() # blank theme for pie charts

Two Dimensions of Data (program X gender)

Stacked Bar Chart

Show the code
ggplot(clients, # data I am using
       aes(x = program, # x is back to program
           fill = gender)) + # fill is gender
  geom_bar() # use bars

Unstack the Bars

Show the code
ggplot(clients, # data I am using
       aes(x = program, # x is back to program
           fill = gender)) + # fill is gender
  geom_bar(position = "dodge2") # unstack ('dodge') the bars

Pie Chart

One approach …

Show the code
# position = position_fill() makes the slices
# fill the pie in each facet

ggplot(clients, # data I am using
       aes(x = 1, # x is back to 1
           fill = gender)) + # fill is gender
  geom_bar(position = position_fill()) + # use bars
  coord_polar(theta = "y") + # polar coordinates
  facet_wrap(~program) + # facet wrap on program
  theme_void() # blank theme for pie charts