Week 9 Class Work

Class work

library(tidyverse)
── Attaching core tidyverse packages ──────────────────────── tidyverse 2.0.0 ──
✔ dplyr     1.2.1     ✔ readr     2.2.0
✔ forcats   1.0.1     ✔ stringr   1.6.0
✔ ggplot2   4.0.3     ✔ tibble    3.3.1
✔ lubridate 1.9.5     ✔ tidyr     1.3.2
✔ purrr     1.2.2     
── Conflicts ────────────────────────────────────────── tidyverse_conflicts() ──
✖ dplyr::filter() masks stats::filter()
✖ dplyr::lag()    masks stats::lag()
ℹ Use the conflicted package (<http://conflicted.r-lib.org/>) to force all conflicts to become errors
library(ggplot2)
library(plotly)

Attaching package: 'plotly'

The following object is masked from 'package:ggplot2':

    last_plot

The following object is masked from 'package:stats':

    filter

The following object is masked from 'package:graphics':

    layout
library(dslabs)
library(gganimate)
library(gapminder)

Attaching package: 'gapminder'

The following object is masked from 'package:dslabs':

    gapminder
library(gifski)
library(highcharter)
Registered S3 method overwritten by 'quantmod':
  method            from
  as.zoo.data.frame zoo 

Attaching package: 'highcharter'

The following object is masked from 'package:dslabs':

    stars
library(RColorBrewer)
disease_democ <- read_csv("disease_democ.csv")
Rows: 168 Columns: 4
── Column specification ────────────────────────────────────────────────────────
Delimiter: ","
chr (2): country, income_group
dbl (2): democ_score, infect_rate

ℹ Use `spec()` to retrieve the full column specification for this data.
ℹ Specify the column types or set `show_col_types = FALSE` to quiet this message.
tail(disease_democ)
# A tibble: 6 × 4
  country       income_group        democ_score infect_rate
  <chr>         <chr>                     <dbl>       <dbl>
1 Turkey        Upper middle income        54.8          39
2 Panama        Upper middle income        46            40
3 Gabon         Upper middle income        34.6          41
4 Venezuela, RB Upper middle income        41.6          42
5 Colombia      Upper middle income        44.8          43
6 Brazil        Upper middle income        37.2          45
head(disease_democ)
# A tibble: 6 × 4
  country      income_group          democ_score infect_rate
  <chr>        <chr>                       <dbl>       <dbl>
1 Bahrain      High income: non-OECD        45.6          23
2 Bahamas, The High income: non-OECD        48.4          24
3 Qatar        High income: non-OECD        50.4          24
4 Latvia       High income: non-OECD        52.8          25
5 Barbados     High income: non-OECD        46            26
6 Singapore    High income: non-OECD        64            26
unique(disease_democ$income_group)
[1] "High income: non-OECD" "High income: OECD"     "Low income"           
[4] "Lower middle income"   "Upper middle income"  
# What this line of code does is find and display all unique variables in the income_group colomn from the selected dataset (disease_democ). We use the dollar sign because it is a R function, not a tidyverse function.
n_distinct(disease_democ$country)
[1] 168
# What this line of code is doing is counting and displaying how many unique variables are in this one selected colomn in the selected datatset. There are 168 countries.
disease_democ |> filter(country == "Qatar") |> pull(income_group)
[1] "High income: non-OECD"
names(postscriptFonts())
 [1] "serif"                "sans"                 "mono"                
 [4] "AvantGarde"           "Bookman"              "Courier"             
 [7] "Helvetica"            "Helvetica-Narrow"     "NewCenturySchoolbook"
[10] "Palatino"             "Times"                "URWGothic"           
[13] "URWBookman"           "NimbusMon"            "NimbusSan"           
[16] "URWHelvetica"         "NimbusSanCond"        "CenturySch"          
[19] "URWPalladio"          "NimbusRom"            "URWTimes"            
[22] "URW2Helvetica"        "URW2HelveticaItalic"  "URW2Times"           
[25] "NimbusMonoPS"         "ArialMT"              "ComputerModern"      
[28] "ComputerModernItalic" "Japan1"               "Japan1HeiMin"        
[31] "Japan1GothicBBB"      "Japan1Ryumin"         "Korea1"              
[34] "Korea1deb"            "CNS1"                 "GB1"                 
disease_democ_chart <-ggplot(disease_democ, aes(x = infect_rate, y = democ_score)) +
  labs(x="Infectious Disease Prevalence Score",
       y="Democratization Score",
       title="Comparison of Disease Prevalence and Democratization Score",
       text = "country") +
  theme_minimal(base_family = "serif")
disease_democ_chart
Ignoring unknown labels:
• text : "country"

disease_democ_chart +
  geom_point(size = 3, alpha = 0.5) +
  geom_smooth(method = lm, se=FALSE, color = "red")
Ignoring unknown labels:
• text : "country"
`geom_smooth()` using formula = 'y ~ x'

# Alpha changes the opacity
p <- disease_democ_chart +
  geom_point(size = 2.5, alpha = 0.5, aes(color = income_group)) +
  geom_smooth(method = lm, se = FALSE, color = "black", lty = 2, linewith = 0.3)
Warning in geom_smooth(method = lm, se = FALSE, color = "black", lty = 2, :
Ignoring unknown parameters: `linewith`
p <- ggplotly(p)
Ignoring unknown labels:
• text : "country"
`geom_smooth()` using formula = 'y ~ x'
p
ggplot(disease_democ, aes(x = infect_rate, y = democ_score, color=income_group)) +
  labs(x="Infectious Disease Prevalence Score",
       y="Democratization Score",
       title="Comparison of Disease Prevalence and Democratization Score") +
  theme_minimal(base_size = 14, base_family = "serif") + 
  geom_point(size = 3, alpha = 0.5) +
  geom_smooth(method=lm, se=FALSE, lty = 2, linewidth = 0.3)
`geom_smooth()` using formula = 'y ~ x'

data(package="dslabs")
list.files(system.file("script", package = "dslabs"))
 [1] "make-admissions.R"                   
 [2] "make-brca.R"                         
 [3] "make-brexit_polls.R"                 
 [4] "make-calificaciones.R"               
 [5] "make-death_prob.R"                   
 [6] "make-divorce_margarine.R"            
 [7] "make-gapminder-rdas.R"               
 [8] "make-greenhouse_gases.R"             
 [9] "make-historic_co2.R"                 
[10] "make-mice_weights.R"                 
[11] "make-mnist_127.R"                    
[12] "make-mnist_27.R"                     
[13] "make-movielens.R"                    
[14] "make-murders-rda.R"                  
[15] "make-na_example-rda.R"               
[16] "make-nyc_regents_scores.R"           
[17] "make-olive.R"                        
[18] "make-outlier_example.R"              
[19] "make-polls_2008.R"                   
[20] "make-polls_us_election_2016.R"       
[21] "make-pr_death_counts.R"              
[22] "make-reported_heights-rda.R"         
[23] "make-research_funding_rates.R"       
[24] "make-results_us_election_2012.R"     
[25] "make-stars.R"                        
[26] "make-temp_carbon.R"                  
[27] "make-tissue-gene-expression.R"       
[28] "make-trump_tweets.R"                 
[29] "make-weekly_us_contagious_diseases.R"
[30] "save-gapminder-example-csv.R"        
p <- ggplot(gapminder, aes(gdpPercap, lifeExp, size = pop, color = continent)) +
  geom_point(alpha = 0.7) +
  scale_color_viridis_d() +
  scale_size(range =c(2, 12)) +
  scale_x_log10() +
  labs(
    title = "Year: {frame_time}",
    x = "GDP per capita",
    y ="Life expectancy")
p

anim <- p +
  transition_time(year) +
  ease_aes("linear")
anim

nations <- read_csv("nations.csv") |>
  mutate(gdp_tn = gdp_percap*population/10^12)
Rows: 5275 Columns: 10
── Column specification ────────────────────────────────────────────────────────
Delimiter: ","
chr (5): iso2c, iso3c, country, region, income
dbl (5): year, gdp_percap, population, birth_rate, neonat_mortal_rate

ℹ Use `spec()` to retrieve the full column specification for this data.
ℹ Specify the column types or set `show_col_types = FALSE` to quiet this message.
str(nations)
tibble [5,275 × 11] (S3: tbl_df/tbl/data.frame)
 $ iso2c             : chr [1:5275] "AD" "AD" "AD" "AD" ...
 $ iso3c             : chr [1:5275] "AND" "AND" "AND" "AND" ...
 $ country           : chr [1:5275] "Andorra" "Andorra" "Andorra" "Andorra" ...
 $ year              : num [1:5275] 1996 1994 2003 1990 2009 ...
 $ gdp_percap        : num [1:5275] NA NA NA NA NA NA NA NA NA NA ...
 $ population        : num [1:5275] 64291 62707 74783 54511 85474 ...
 $ birth_rate        : num [1:5275] 10.9 10.9 10.3 11.9 9.9 NA 10.9 9.8 11.8 11.2 ...
 $ neonat_mortal_rate: num [1:5275] 2.8 3.2 2 4.3 1.7 1.6 2 1.7 2.1 2.1 ...
 $ region            : chr [1:5275] "Europe & Central Asia" "Europe & Central Asia" "Europe & Central Asia" "Europe & Central Asia" ...
 $ income            : chr [1:5275] "High income" "High income" "High income" "High income" ...
 $ gdp_tn            : num [1:5275] NA NA NA NA NA NA NA NA NA NA ...
# 5275 observations and 11 variables
big4 <- nations |>
  filter(iso3c %in% c("CHN","DEU", "JPN", "USA")) |>
  arrange(year)
highchart() |>
  hc_add_series(data = big4,
                type = "line", 
                hcaes(x = year,
                      y = gdp_tn, 
                      group = country))
cols <- brewer.pal(4, "Set1")

highchart() |>
  hc_add_series(data = big4,
                type = "line", hcaes(x = year,
                                     y = gdp_tn, 
                                     group = country)) |>
  hc_colors(cols)
highchart() |>
  hc_add_series(data = big4,
                type = "line",
                hcaes(x = year,
                      y = gdp_tn, 
                      group = country)) |>
  hc_colors(cols) |>
  hc_xAxis(title = list(text="Year")) |>
  hc_yAxis(title = list(text="GDP ($ trillion)"))
highchart() |>
  hc_add_series(data = big4,
                type = "line",
                hcaes(x = year,
                      y = gdp_tn, 
                      group = country)) |>
  hc_colors(cols) |>
  hc_xAxis(title = list(text="Year")) |>
  hc_yAxis(title = list(text="GDP ($ trillion)")) |>
  hc_plotOptions(series = list(marker = list(symbol = "circle"))) |>
  hc_legend(align = "left", 
            verticalAlign = "top")
big4_chart <- highchart() |>
  hc_add_series(data = big4,
                type = "line",
                hcaes(x = year,
                      y = gdp_tn, 
                      group = country)) |>
  hc_colors(cols) |>
  hc_xAxis(title = list(text="Year")) |>
  hc_yAxis(title = list(text="GDP ($ trillion)")) |>
  hc_plotOptions(series = list(marker = list(symbol = "circle"))) |>
  hc_legend(align = "right", 
            verticalAlign = "top") |>
  hc_tooltip(shared = TRUE,
             borderColor = "black",
             pointFormat = "{point.country}: {point.gdp_tn:.2f}")
big4_chart
regions <- nations |>
  group_by(year,region) |>
  summarize(gdp_tn = sum(gdp_tn, na.rm = TRUE)) |>
  arrange(year,region)
`summarise()` has regrouped the output.
ℹ Summaries were computed grouped by year and region.
ℹ Output is grouped by year.
ℹ Use `summarise(.groups = "drop_last")` to silence this message.
ℹ Use `summarise(.by = c(year, region))` for per-operation grouping
  (`?dplyr::dplyr_by`) instead.
highchart () |>
  hc_add_series(data = regions,
                type = "area",
                hcaes(x = year,
                      y = gdp_tn, 
                      group = region))
cols <- brewer.pal(7, "Set2")

# stacked area chart
highchart () |>
  hc_add_series(data = regions,
                type = "area",
                hcaes(x = year,
                      y = gdp_tn, 
                      group = region)) |>
  hc_colors(cols) |> 
  hc_chart(style = list(fontFamily = "Georgia",
                        fontWeight = "bold")) |>
  hc_plotOptions(series = list(stacking = "normal",
                               marker = list(enabled = FALSE,
                                             states = list(hover = list(enabled = FALSE))),
                               lineWidth = 0.5,
                               lineColor = "white")) |>
  hc_xAxis(title = list(text="Year")) |>
  hc_yAxis(title = list(text="GDP ($ trillion)")) |>
  hc_legend(align = "right", verticalAlign = "top",
            layout = "vertical") 

Week 9 Class Work

ggplot(big4, aes(year, gdp_tn, color = country)) +
  geom_point(alpha = 1) +
  geom_line() +
  scale_color_brewer(palette = "Set1") +
  labs(title = "China's Rise to Become the Largest Economy",
       x = "year",
       y = "GDP ($ trillion)")

Chart 2

ggplot(regions, aes(year, gdp_tn, fill = region)) +
  geom_area(position = "stack") +
  labs(title = "GDP by World Bank Region",
       x= "year",
       y = "GDP ($ trillion)") +
  scale_fill_brewer(palette = "Set2")