DACSS 601 Challenge5

Introduction to Visualization
Author

Calvin Cuff

Published

January 8, 2024

Code
library(dplyr)
library(here)
library(readr)
library(tidyverse)
library(autoimage)

Read in data

Read in one (or more) of the following datasets, using the correct R package and command.

  • Public School Characteristics ⭐⭐⭐⭐
Code
pub <- read_csv(here("data", "Public_School_Characteristics_2017-18.csv"))
Warning: One or more parsing issues, call `problems()` on your data frame for details,
e.g.:
  dat <- vroom(...)
  problems(dat)
Rows: 100729 Columns: 79
── Column specification ────────────────────────────────────────────────────────
Delimiter: ","
chr (25): NCESSCH, NMCNTY, SURVYEAR, STABR, LEAID, ST_LEAID, LEA_NAME, SCH_N...
dbl (51): X, Y, OBJECTID, TOTFRL, FRELCH, REDLCH, PK, KG, G01, G02, G03, G04...
lgl  (3): LSTREET3, G13, AE

ℹ 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.
Code
head(pub)
# A tibble: 6 × 79
      X     Y OBJECTID NCESSCH     NMCNTY SURVYEAR STABR LEAID ST_LEAID LEA_NAME
  <dbl> <dbl>    <dbl> <chr>       <chr>  <chr>    <chr> <chr> <chr>    <chr>   
1 -149.  61.6        1 0200510004… Matan… 2017-20… AK    0200… AK-33    Matanus…
2 -157.  71.3        2 0200610004… North… 2017-20… AK    0200… AK-36    North S…
3 -151.  60.5        3 0200390004… Kenai… 2017-20… AK    0200… AK-24    Kenai P…
4 -151.  60.6        4 0200390004… Kenai… 2017-20… AK    0200… AK-24    Kenai P…
5 -151.  60.6        5 0200390005… Kenai… 2017-20… AK    0200… AK-24    Kenai P…
6 -133.  56.1        6 0200700005… Princ… 2017-20… AK    0200… AK-44    Southea…
# ℹ 69 more variables: SCH_NAME <chr>, LSTREET1 <chr>, LSTREET2 <chr>,
#   LSTREET3 <lgl>, LCITY <chr>, LSTATE <chr>, LZIP <chr>, LZIP4 <chr>,
#   PHONE <chr>, GSLO <chr>, GSHI <chr>, VIRTUAL <chr>, TOTFRL <dbl>,
#   FRELCH <dbl>, REDLCH <dbl>, PK <dbl>, KG <dbl>, G01 <dbl>, G02 <dbl>,
#   G03 <dbl>, G04 <dbl>, G05 <dbl>, G06 <dbl>, G07 <dbl>, G08 <dbl>,
#   G09 <dbl>, G10 <dbl>, G11 <dbl>, G12 <dbl>, G13 <lgl>, TOTAL <dbl>,
#   MEMBER <dbl>, AM <dbl>, HI <dbl>, BL <dbl>, WH <dbl>, HP <dbl>, TR <dbl>, …

Briefly describe the data

Code
dim(pub)
[1] 100729     79
Code
colnames(pub)
 [1] "X"                "Y"                "OBJECTID"         "NCESSCH"         
 [5] "NMCNTY"           "SURVYEAR"         "STABR"            "LEAID"           
 [9] "ST_LEAID"         "LEA_NAME"         "SCH_NAME"         "LSTREET1"        
[13] "LSTREET2"         "LSTREET3"         "LCITY"            "LSTATE"          
[17] "LZIP"             "LZIP4"            "PHONE"            "GSLO"            
[21] "GSHI"             "VIRTUAL"          "TOTFRL"           "FRELCH"          
[25] "REDLCH"           "PK"               "KG"               "G01"             
[29] "G02"              "G03"              "G04"              "G05"             
[33] "G06"              "G07"              "G08"              "G09"             
[37] "G10"              "G11"              "G12"              "G13"             
[41] "TOTAL"            "MEMBER"           "AM"               "HI"              
[45] "BL"               "WH"               "HP"               "TR"              
[49] "FTE"              "LATCOD"           "LONCOD"           "ULOCALE"         
[53] "STUTERATIO"       "STITLEI"          "AMALM"            "AMALF"           
[57] "ASALM"            "ASALF"            "HIALM"            "HIALF"           
[61] "BLALM"            "BLALF"            "WHALM"            "WHALF"           
[65] "HPALM"            "HPALF"            "TRALM"            "TRALF"           
[69] "TOTMENROL"        "TOTFENROL"        "STATUS"           "UG"              
[73] "AE"               "SCHOOL_TYPE_TEXT" "SY_STATUS_TEXT"   "SCHOOL_LEVEL"    
[77] "AS"               "CHARTER_TEXT"     "MAGNET_TEXT"     
Code
length(unique(pub$STABR))
[1] 56
Code
tmp <- pub %>% filter(! STABR %in% state.abb) %>%
  select(STABR)

unique(tmp$STABR)
[1] "AS" "DC" "PR" "VI" "BI" "GU"

This data set describes a large number of characteristics of public elementary and secondary schools from the 2017-2018 school year from all 50 US states, as well as 6 other territories including Puerto Rico, Guam, and others. There are 100729 rows and 79 columns describing the school’s specific location plus some points from a previous graph. As well as a very detailed view of the school’s student demographics, broken down by race and gender. There are some additional columns for school programs such as Title 1, lunch programs, and school type, such as charter, plus many more. A full detailed list of the columns and the abbreviations’ meanings can be found here.

Tidy Data (as needed)

Is your data already tidy, or is there work to be done? Be sure to anticipate your end result to provide a sanity check, and document your work here.

For the most part, this data is already fairly tidy, except for the column names which are frustrating abbreviations, and there are so many. Let’s reread the data and rename the columns to something readable, marking many columns that are not important with “del” to filter out.

Code
pub_tidy <- read_csv(here("data", "Public_School_Characteristics_2017-18.csv"),
                col_names = c("x","y","del", "del", "county", "del", "del", "del", 
                              "del", "del", "del", "del", "del", "del", "del", "state", 
                              "del", "del", "del", "low_grade", "high_grade", "virtual", 
                              "del", "free_lunch", "red_lunch", "pre_k", "kdg", "g1",
                              "g2", "g3", "g4", "g5", "g6", "g7", "g8", "g9", "g10", "g11", 
                              "g12", "g13", "total_students", "total_elem_second_students",
                              "native_am", "hispanic", "black", "white",  "pacific", "two_or_more",
                              "total_teachers", "latitude", "longitude", "locale", "student_teach_ratio", 
                              "title_1", "native_male", "native_fem", "asian_male", "asian_fem", 
                              "hispanic_male", "hispanic_fem", "black_male", "black_fem", "white_male", 
                              "white_fem", "pacific_male", "pacific_fem", "two_races_male", "two_races_fem", 
                              "male_enroll", "female_enroll", "del", "ungraded_stud", "adult_ed", 
                              "type", "status", "level", "asian", "is_charter", "is_magnet"), 
                skip = 1) %>%
  select(!contains("del"))
New names:
• `del` -> `del...3`
• `del` -> `del...4`
• `del` -> `del...6`
• `del` -> `del...7`
• `del` -> `del...8`
• `del` -> `del...9`
• `del` -> `del...10`
• `del` -> `del...11`
• `del` -> `del...12`
• `del` -> `del...13`
• `del` -> `del...14`
• `del` -> `del...15`
• `del` -> `del...17`
• `del` -> `del...18`
• `del` -> `del...19`
• `del` -> `del...23`
• `del` -> `del...71`
Warning: One or more parsing issues, call `problems()` on your data frame for details,
e.g.:
  dat <- vroom(...)
  problems(dat)
Rows: 100729 Columns: 79
── Column specification ────────────────────────────────────────────────────────
Delimiter: ","
chr (25): del...4, county, del...6, del...7, del...8, del...9, del...10, del...
dbl (51): x, y, del...3, del...23, free_lunch, red_lunch, pre_k, kdg, g1, g2...
lgl  (3): del...14, g13, adult_ed

ℹ 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.
Code
head(pub_tidy)
# A tibble: 6 × 62
      x     y county     state low_grade high_grade virtual free_lunch red_lunch
  <dbl> <dbl> <chr>      <chr> <chr>     <chr>      <chr>        <dbl>     <dbl>
1 -149.  61.6 Matanuska… AK    PK        05         Not a …        158        25
2 -157.  71.3 North Slo… AK    09        12         Not a …         27         0
3 -151.  60.5 Kenai Pen… AK    KG        06         Not a …         23        20
4 -151.  60.6 Kenai Pen… AK    KG        05         Not a …         50        19
5 -151.  60.6 Kenai Pen… AK    07        12         Not a …         -9        -9
6 -133.  56.1 Prince of… AK    PK        12         Not a …         17         0
# ℹ 53 more variables: pre_k <dbl>, kdg <dbl>, g1 <dbl>, g2 <dbl>, g3 <dbl>,
#   g4 <dbl>, g5 <dbl>, g6 <dbl>, g7 <dbl>, g8 <dbl>, g9 <dbl>, g10 <dbl>,
#   g11 <dbl>, g12 <dbl>, g13 <lgl>, total_students <dbl>,
#   total_elem_second_students <dbl>, native_am <dbl>, hispanic <dbl>,
#   black <dbl>, white <dbl>, pacific <dbl>, two_or_more <dbl>,
#   total_teachers <dbl>, latitude <dbl>, longitude <dbl>, locale <chr>,
#   student_teach_ratio <dbl>, title_1 <chr>, native_male <dbl>, …

Are there any variables that require mutation to be usable in your analysis stream? For example, do you need to calculate new values in order to graph them? Can string values be represented numerically? Do you need to turn any variables into factors and reorder for ease of graphics and visualization?

Document your work here.

There are a few interesting values that can be calculated that I would like to make columns for, although they could be done on the fly. I will make columns for the total number of minority students by school, the percentage of the school that is made up of minorities, and the percentage of the school that qualifies for their free or reduced price lunch programs.

Code
pub_tidy <- pub_tidy %>%
  # Add all the different minority groups
  mutate(minorities = native_am + hispanic + black + pacific + two_or_more +asian,
         # Calculate the minority percentage
         pct_minority = minorities/total_students *100,
         # Calculate the free or reduced lunch percentage
         pct_free_or_reduced_lunch = (free_lunch + red_lunch)/total_students * 100) 

Univariate Visualizations

There are a number of nominal variables that we can visualize to get a better understanding of the types of schools that were included in this study.

If we graph the statuses of the schools we can see that the number of Currently operational schools is the clear favorite, with all other types being very minimal. This is a good data point to understand that at the time of the survey the schools were up and running. We can also add a fill to add color to the graph and add a theme to omit the x axis text due to the long group names, replaced by the neat sidebar legend.

Code
ggplot(pub_tidy, aes(status, fill=status)) + geom_bar() + theme(axis.text.x = element_blank())

By graphing the type of school we can also see that almost all of the schools are ‘Regular’. There are some other types of schools such as Alternative, Special Ed, and Vocational but they are small in number compared to the Regular. It is possible that the type of school could influence the diversity enrollment numbers, but if we look at the study as a whole it should not influence the data too much given the smaller sample size. Adding a fill and dark theme to this graph also presents the data in a more visually appealing way.

Code
ggplot(pub_tidy, aes(type, fill=type)) + geom_bar() + theme_dark()

We can also graph a histogram of the percentage of enrolled students that identify as a minority group to show the frequency distribution across the schools in the study. We can see there is a very big dispersion but the tail ends of low diversity and high diversity seem to have more representation.

Code
ggplot(pub_tidy, aes(pct_minority)) + geom_histogram(aes(y = ..density..), alpha = 0.5)  + geom_density(alpha = 0.2, fill="red")
Warning: The dot-dot notation (`..density..`) was deprecated in ggplot2 3.4.0.
ℹ Please use `after_stat(density)` instead.
`stat_bin()` using `bins = 30`. Pick better value with `binwidth`.
Warning: Removed 37192 rows containing non-finite values (`stat_bin()`).
Warning: Removed 37192 rows containing non-finite values (`stat_density()`).

Bivariate Visualization(s)

To get a picture of the relationship between the density of diverse students and the percentage of overall students who qualify for free or reduced price lunch programs, we can create a scatter plot against those two variables. I will filter out some values that have invalid percentages and use geom_smooth() to add a trend line of the points. We can see that while there is a lot of data all over the place, there is a linear trend that indicates higher percentages of minority students result in more students that qualify for discounted lunch programs.

Code
pub_tidy %>%
  filter(pct_free_or_reduced_lunch >= 0 & pct_free_or_reduced_lunch <= 100) %>%
  ggplot(aes(pct_minority, pct_free_or_reduced_lunch)) + geom_point() +   geom_smooth(method='lm')
`geom_smooth()` using formula = 'y ~ x'
Warning: Removed 30345 rows containing non-finite values (`stat_smooth()`).
Warning: Removed 30345 rows containing missing values (`geom_point()`).

We can also use a geom_boxplot() to visualize the diversity dispersion across different school locales, such as city and size vs rural and remote. Adding a fill to the graph will give us color to easily identify the locale group given that there are a number of them, while rotating x-axis labels help to preserve the overall readability.

Code
pub_tidy %>%
  ggplot(aes(locale, pct_minority, fill=locale)) + geom_boxplot( ) +theme(axis.text.x = element_text(angle = 90))
Warning: Removed 37192 rows containing non-finite values (`stat_boxplot()`).

I am curious what the x and y variables are for. It was noted that they were referenced as the shape from some previous graph, but I’m not sure what for. If we create a scatter plot we end up with a pretty realistic map of the US states and its territories.

Code
ggplot(pub_tidy, aes(x, y)) + geom_point()

That is a pretty cool starting point to work with. Next let’s filter out the the rows to just include the continental US to get a more enhanced visualization. Given that each point is a school location, I am also going to overlay a heat map of the percentage of minority students to see if we can easily identify any patterns indicating which locations may have higher diversity rates. For this visualization I used the autopoints() function from the autoimage package which includes some cool built in functionality for visual overlays. From the colored graph we can see that there definitely seems to be a trend that favors higher diversity rates in the southern and coastal regions, perhaps where immigration might be more feasible. The middle and northern states indicates much lower levels of minority groups shown by the darker shades in the graph.

Code
# Filter to just continental US, easier to visualize
us_pub <- pub_tidy %>%
  filter(state %in% state.abb & !state %in% c("HI", "AK"))
  
# Graph point locations with minority visualization
autopoints(us_pub$x, us_pub$y, us_pub$pct_minority, 
       # labels
       xlab = "lat", ylab = "long",
       # Specify color palette
       col = colorspace::sequential_hcl(n = 20, palette = "viridis"),
       # Break up pct_minority 0-100 in chunks of 5
       breaks = seq(0, 100, by = 5))