temo
temo

Reputation: 69

Using facet_wrap from function/dataset?

I have the function I wrote below, and I used ggplot2 to create a plot of how many males and females there are for each one (from the babynames dataset).

library(babynames)
anna <- babynames %>%
  filter(name == "Anna", year >=1920) %>%
  group_by(year, sex) %>%
  summarise(n = sum(n)) %>%
  mutate(n = n/sum(n, na.rm = TRUE) * 100) 
anna_plot <- ggplot(anna, aes(x = year, y = n, fill = sex)) +
  geom_area(position = 'stack', color="black")
anna_plot

While I can create this plot for individual names, like a graph showing Anna, I want to create a plot where it shows all of the names I am examining in one plot. (Like a facet wrap?)

So for example, how would I go about creating a plot for 4 names, like Anna, Henry, Casey, and Dana. Would I need map_df?

Upvotes: 1

Views: 176

Answers (1)

stefan
stefan

Reputation: 124148

Basically it is the same approach. You just filter for all four names or the names you want, than also group_by name. Try this:

library(babynames)
#> Warning: package 'babynames' was built under R version 3.6.3
library(dplyr)
#> 
#> Attaching package: 'dplyr'
#> The following objects are masked from 'package:stats':
#> 
#>     filter, lag
#> The following objects are masked from 'package:base':
#> 
#>     intersect, setdiff, setequal, union
library(ggplot2)

df <- babynames %>%
  filter(name %in% c("Anna", "Henry", "Casey", "Dana"),
         year >=1920) %>%
  group_by(name, year, sex) %>%
  summarise(n = sum(n)) %>%
  mutate(n = n / sum(n, na.rm = TRUE) * 100) %>% 
  # Example of reorder names and sex
  ungroup() %>% 
  mutate(name = factor(name, c("Anna", "Dana", "Casey", "Henry")),
         sex = factor(sex, c("M", "F")))

ggplot(df, aes(x = year, y = n, fill = sex)) +
  geom_area(position = 'stack', color="black") +
  facet_wrap(~name)

Created on 2020-03-08 by the reprex package (v0.3.0)

Upvotes: 2

Related Questions