---
title: "Histograms"
output: html_document
---

```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
library(tidyverse)
library(gapminder)
```

### Histograms

```{r}
titanic <- read.csv("http://guerzhoy.princeton.edu/201s20/titanic.csv")
```

A more typical situation is plotting the histogram of a continous variable like age. 

```{r}
ggplot(data = titanic,  mapping = aes(x = Age)) +
      geom_histogram(bins = 50)
```

Varying the number of bins allows us to display the data more appropriately: too many bins means we'll see patterns that aren only there because the sample size is too small; too few bins means we won't see trends that *are* actually in the data.

```{r}
ggplot(data = titanic,  mapping = aes(x = Age)) +
      geom_histogram(bins = 100)
```

```{r}
ggplot(data = titanic,  mapping = aes(x = Age)) +
      geom_histogram(bins = 3)
```


We can display overlapping histograms. We specify `alpha = 0.4` to indicate that the histograms are partially transparent.


```{r}
ggplot(data = titanic, mapping = aes(x = Age, fill = relevel(as.factor(Sex), ref = "male") )) +
  geom_histogram(alpha = 0.4, bins = 10, position = "identity")
```


Note that the default position is `"stack"`.

```{r}
ggplot(data = titanic, mapping = aes(x = Age, fill = Sex)) +
  geom_histogram(alpha = 0.4, bins = 10, position = "stack")
```

Here is the same histogram with position `"dodge"`

```{r}
ggplot(data = titanic, mapping = aes(x = Age, fill = Sex)) +
  geom_histogram(alpha = 0.4, bins = 10, position = "dodge")
```


