Skip to content

Instantly share code, notes, and snippets.

@dgkeyes
Created April 26, 2019 14:24
Show Gist options
  • Save dgkeyes/328cf330ed39fa330a8a36de4fa9e5f8 to your computer and use it in GitHub Desktop.
Save dgkeyes/328cf330ed39fa330a8a36de4fa9e5f8 to your computer and use it in GitHub Desktop.
facets solutions
# Facets
I've created a data frame called `sleep_by_gender_by_age` for you. Run the code chunk below to load the data frame.
```{r}
sleep_by_gender_by_age <- nhanes %>%
group_by(gender, age_decade) %>%
summarize(avg_sleep = mean(sleep_hrs_night, na.rm = TRUE)) %>%
drop_na()
```
Let's take a look at `sleep_by_gender_by_age`.
```{r}
sleep_by_gender_by_age
```
Now, see if you can recreate this plot. Much of the code will be the same from your previous plots using the `sleep_by_gender` data frame so just make some small changes.
![](plots/sleep-by-gender-by-age.png)
```{r}
ggplot(data = sleep_by_gender_by_age,
aes(x = age_decade,
y = avg_sleep,
fill = gender)) +
geom_col(show.legend = FALSE) +
geom_text(aes(label = round(avg_sleep, 1)),
vjust = 1.5,
color = "white") +
scale_y_continuous(limits = c(0, 8),
breaks = seq(0, 8, by = 1)) +
scale_fill_brewer(palette = "Dark2") +
facet_wrap(~gender) +
theme_ipsum() +
labs(title = "Sleep by gender and age",
y = "Hours of sleep per night",
x = "")
```
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment