```{r}
library(ggplot2)
```

```{r}
g <- ggplot(midwest, aes(x = area, y = poptotal))
g + geom_point() + xlim(c(0, 0.1)) + ylim(0, 1000000) + geom_smooth()
g + geom_point() + coord_cartesian(xlim = c(0, 0.1), ylim = c(0, 1000000)) + geom_smooth()
```

```{r}
g <- g + geom_point() + coord_cartesian(xlim = c(0, 0.1), ylim = c(0, 1000000)) + geom_smooth()
g + labs(y = "Population", x = "Area", title = "Area vs Population", subtitle = "From midwest data source")
```

Add color:
```{r}
g <- ggplot(midwest, aes(x = area, y = poptotal))
g <- g + geom_point(col = "darkgreen", size = 2) + coord_cartesian(xlim = c(0, 0.1), ylim = c(0, 1000000)) + geom_smooth(col = "red")
g + labs(y = "Population", x = "Area", title = "Area vs Population", subtitle = "From midwest data source")
```


```{r}
g <- ggplot(midwest, aes(x = area, y = poptotal))
g <- g + geom_point(aes(col = state), size = 2) + coord_cartesian(xlim = c(0, 0.1), ylim = c(0, 1000000)) + geom_smooth(col = "red") + scale_colour_brewer(palette = "Set3")
g + labs(y = "Population", x = "Area", title = "Area vs Population", subtitle = "From midwest data source")
```


```{r}
library(ggalt)

selected <- midwest[midwest$poptotal > 250000 & midwest$poptotal < 500000, ]

g <- ggplot(midwest, aes(x = area, y = poptotal))
g <- g + geom_point(aes(col = state), size = 2) + xlim(0, 0.1) + ylim(0, 500000) + geom_smooth(col = "red") + scale_colour_brewer(palette = "Set3")
g + labs(y = "Population", x = "Area", title = "Area vs Population", subtitle = "From midwest data source") + geom_encircle(aes(x = area, y = poptotal), data = selected, color = "red", size = 3, expand = 0.05)
```



```{r}
data(mpg, package="ggplot2")
g <- ggplot(mpg, aes(x = cty, y = hwy))
g <- g + geom_jitter() + geom_smooth(method = "lm")
plot(g)
```

```{r}
g <- ggplot(mpg, aes(x = cty, y = hwy))
g <- g + geom_count(col = "darkred") + geom_smooth(method = "lm")
plot(g)
```

## Histogram

```{r}
g <- ggplot(mpg, aes(displ))

g + geom_histogram(aes(fill = class), bins = 5)
```

## Density

```{r}
g <- ggplot(mpg, aes(hwy))
#g + geom_density(fill = "red")
g + geom_density(aes(fill = factor(year)), alpha = 0.8)
```

## Box plot

```{r}
g <- ggplot(mpg, aes(class, cty))
g + geom_boxplot() + geom_dotplot(binaxis = "y", dotsize = 0.5, stackdir = "center")
```

## Lazy evaluation

```{r}
g <- ggplot()

for (j in 1:10) {
  g <- g + geom_point(aes(x = j, y = j))
  #g <- g + geom_point(aes_(x = j, y = j))
}
print(g)
```
