---
title: "Some Data Visualization"
author: "Colin Kuehl"
date: "2022-11-10"
output: html_document
always_allow_html: true
geometry: margin=1in
fontfamily: libertine
fontsize: 11pt
editor_options: 
  chunk_output_type: console
  markdown: 
    wrap: 72
---

```{r setup, include=FALSE}
knitr::opts_chunk$set(cache = FALSE,
  message = FALSE, warning = FALSE,
  tidy.opts = list(width.cutoff = 80), tidy = TRUE)
```

Welcome to data visualization

# Section 1

First, while we have used Rmarkdown all semester we have not discussed
its value as a word processer.

There are all sorts of things you can in Markdown. For example, you
could make a list of helpful links.

- [R Markdown Cookbook](https://bookdown.org/yihui/rmarkdown-cookbook/)
- [R Markdown Cheat
  Sheet](https://www.rstudio.com/wp-content/uploads/2015/02/rmarkdown-cheatsheet.pdf)
- [Markdown Guide](https://www.markdownguide.org/cheat-sheet/)
- [Markdown Templates](https://rmarkdown.rstudio.com/gallery.html)
  -[Daring
  Fireball](https://daringfireball.net/projects/markdown/syntax)
  -[rticles package](https://pkgs.rstudio.com/rticles/)

Or insert an image

![R makes me
smile](https://www.r-project.org/logo/Rlogo.png){width="50%"}

You can write your text *italics* or make things **bold**

You can even use it create citations, but we won't get into that today.

As you've learned(probably the hard way), a key with Rmarkdown is to
continuously knit to make sure you are not making mistakes and look at
what the output looks like.

```{r, include=FALSE}
library(tidyverse)
library(ggplot2)
library(ggthemes)
```

# Some thoughts on Visualization

Visualizing quantitative data is critical to scientific work and moving
beyond basics can enhance the quality of any work that you do. Even if
you are relying primarily on qualitative work a few well done figures
can add tremendous value to your work.

As you read in the Healy book, there aren't many hard and fast rules
when it comes to visualization.

My quick thoughts:[^1]

[^1]: Cool a footnote. These are mostly just my musings.

1.  Keep it simple - only display data critical to your argument. Less
    can be more
2.  Fully label -

- Include axis
- Interpret in your text

3.  Have a clear idea of what you want your reader to get out of each
    figure. Remember, they don't know the data like you do.
4.  Be cognizant of scales
5.  Most journals still publish in greyscale and many people are
    colorblind so you can't rely too much on color variation.
6.  The best way to get good at visualizations is to practice.

“The greatest value of a picture is when it forces us to notice what we
never expected to see.” — John Tukey

You will use data visualizations in two ways. First, is to get know your
own data. There will be lots of these graphs and they don't need to be
"bedazzled." Second, is the actual figures you want to use for public
consumption. As with models, you'll end up using a small portion of all
the figures you use so make them good.

### GGplot

We've already worked in GGplot this semester and for good reason. It is
the premier package for creating figures (even compared to other
software systems). Almost all figures I now produce for publication use
GGplot. Whether we knew it or not there is underlying *"grammar of
graphics"* that [ggplot
uses](https://r4ds.had.co.nz/data-visualisation.html#the-layered-grammar-of-graphics).

ggplot(data = <DATA>) + <GEOM_FUNCTION>( mapping = aes(<MAPPINGS>), stat
= <STAT>, position = <POSITION> ) + <COORDINATE_FUNCTION> +
<FACET_FUNCTION>

- data is a data frame
- Aesthetics is used to indicate x and y variables. It can also be used
  to control the color, the size or the shape of points, the height of
  bars, etc…..
- Geometry corresponds to the type of graphics (histogram, box plot,
  line plot, density plot, dot plot, ….)
- Others are optional

There are a wide variety of graphs you can create in
[ggplot](https://r-graph-gallery.com/). However, the ones we have used
throughout the semester histograms or density plots, scatterplots(with
and without regression lines), bar plots, and box plots will be 90% of
the figures that you use. For each variable of interest you should know
its distribution(histogram or boxplot). For each relationship, you
should know how it plots.

Rather than going through a bunch of examples lets talk through an
example. What is good and bad about this figure?

```{r, echo=FALSE}
ggplot(mpg, aes(displ, hwy)) +
  geom_point(aes(color = class)) +
  geom_smooth(se = FALSE) +
  labs(title = "Fuel efficiency generally decreases with engine size")+theme_bw()
```

Create a better version:

```{r}

```

# Mapping

## Mapping Specific Locations

```{r, echo=FALSE}

#install.packages(c("sf", "mapview", "leaflet", "usmap", "rworldmap"))


library(sf)
library(mapview)
library(readr)
library(leaflet)

starbucks <- read_csv("https://raw.githubusercontent.com/libjohn/mapping-with-R/master/data/All_Starbucks_Locations_in_the_US_-_Map.csv")
```

We can create a map of Starbucks locations

```{r, echo=FALSE}

mapview(starbucks, xcol = "Longitude", ycol = "Latitude", crs = 4269, grid = FALSE)
```

## State Maps

```{r, echo=FALSE}
library(usmap) #https://cran.r-project.org/web/packages/usmap/vignettes/mapping.html
library(ggplot2)

plot_usmap(regions = "counties") + 
  labs(title = "US Counties",
       subtitle = "This is a blank map of the counties of the United States.") + 
  theme(panel.background = element_rect(color = "black", fill = "lightblue"))


starbucksstate <- starbucks %>% count(State)
starbucksstate$state <- starbucksstate$State

states <- left_join(statepop, starbucksstate,by=c("abbr"="state"))

states$percap <- states$pop_2022/states$n

plot_usmap(data = states, values = "n")+ scale_fill_continuous(
    low = "white", high = "darkgreen", name = "# of Starbucks Locations", label = scales::comma
  ) + theme(legend.position = "right")+ labs(title = "Starbucks Across the United States")

plot_usmap(data = states, values = "percap")+ scale_fill_continuous(
    low = "white", high = "darkolivegreen", name = "Population (2015)", label = scales::comma
  ) + theme(legend.position = "right")+labs(title = "Starbucks Per Capita")
```

# Look at Dunkin Donuts

```{r, echo=FALSE}
dunkin <- read_csv("https://raw.githubusercontent.com/trendct/dunkin-donuts-ct/master/dunkindonuts.csv")

mapview(dunkin, xcol = "lng", ycol = "lat", crs = 4269, grid = FALSE)

dunkinstate <- dunkin %>% count(state)


states <- left_join(states, dunkinstate,by=c("abbr"="state"))


plot_usmap(data = states, values = "n.y")+ scale_fill_continuous(
    low = "white", high = "orange", name = "# of dunkin Locations", label = scales::comma
  ) + theme(legend.position = "right")+ labs(title = "dunkin Across the United States")
```

## Global Maps

```{r, echo=FALSE, message=FALSE, warning=FALSE}
#install.packages(c('gapminder',,'gganimate','gifski', 'rworldmap', 'gganimate'))

library(gapminder)#dataset
library(rworldmap)

#summary(gapminder)
#dim(gapminder)

gapmap <-joinCountryData2Map(gapminder,joinCode="ADMIN", nameJoinColumn="country")
par(mai=c(0,0,0.2,0),xaxs="i",yaxs="i") #Trying to use gapminder data(not all seem to convert. could use countrycode to convert to ISO3)

mapCountryData(gapmap, nameColumnToPlot="lifeExp",  mapTitle="Life Expectancy", addLegend=TRUE)

mapCountryData(gapmap, nameColumnToPlot="gdpPercap",  mapTitle="GDP per Capita", colourPalette="rainbow", addLegend=TRUE)#don't use this colour palette
```

# Animation

## Basic Scatterplots

```{r, echo=FALSE}
ggplot(gapminder, aes(gdpPercap, lifeExp, size = pop, colour = country)) +
   geom_point(alpha = 0.7, show.legend = FALSE) +
   scale_colour_manual(values = country_colors) +
   scale_size(range = c(2, 12)) +
   scale_x_log10() +
   facet_wrap(~continent) +
   labs(title = 'Year: 1952-2007', x = 'GDP per capita', y = 'Life expectancy')
```

You can also add R code mid-text. For example, the average GDP per
capita is `r mean(gapminder$gdpPercap)`

Create animation

```{r, echo=FALSE}
library(gganimate)
library(gifski)

p1 <- ggplot(gapminder, aes(gdpPercap, lifeExp, size = pop, colour = country)) +
             geom_point(alpha = 0.7, show.legend = FALSE) +
             scale_colour_manual(values = country_colors) +
             scale_size(range = c(2, 12)) +
             scale_x_log10()  + 
  facet_wrap(~continent) +
             # Animating the plot
             labs(title = 'Year: {frame_time}', x = 'GDP per capita', y = 'Life expectancy') +
             transition_time(year) +
             ease_aes('linear')

animate(p1, renderer = gifski_renderer())
#anim_save('plot_gdpPercap_lifeExp.gif')

#World Together
p2 <- ggplot(gapminder, aes(gdpPercap, lifeExp, size = pop, colour = country)) +
             geom_point(alpha = 0.7, show.legend = FALSE) +
             scale_colour_manual(values = country_colors) +
             scale_size(range = c(2, 12)) +
             scale_x_log10()  +
             # Animating the plot
             labs(title = 'Year: {frame_time}', x = 'GDP per capita', y = 'Life expectancy') +
             transition_time(year) +
             ease_aes('linear')
animate(p2, renderer = gifski_renderer())
```


