#Title: DWV Assign 6 - Mondak Sanders.R
#Author: Jack Reilly
#Purpose: Explore two variables in the gss
#Requires: 1972-2024 Cumulative GSS Data ("gss7224_r1.dta"); expects a particular folder structure in home directory:
      # figures
        # base
        # ggplot
        # lattice
      # scripts
      # writeup
#Output: Figures as PDFs (ggplot only)

library(tidyverse)
library(lattice)

setwd("~/desktop/working/dwv/mondaksanders2026")

# Let's look at support for spending on space exploration

table(gss$natspac)
unique(gss$natspac)

histogram( ~ as.numeric(natspac), data=gss, xlab = "Support for Space Spending")

histogram(~ as.numeric(natspac), data = gss,
          breaks = seq(0.5, 3.5, by = 1),
          scales = list(x = list(at = 1:3,
                                 labels = c("Too little", "About right", "Too much"))),
          xlab = "Support for Space Spending")

gss_space <- gss |>
  mutate(natspac = as.numeric(natspac)) |>
  filter(natspac %in% 1:3) |>
  group_by(year) |>
  summarize(natspac = mean(natspac), n = n())

spaceplot<-ggplot(gss_space, aes(x = year, y = natspac)) +
  geom_line(linewidth = 1) +
  geom_point(size = 1.5) +
  scale_y_continuous(limits = c(1, 3), breaks = 1:3,
                     labels = c("Too little", "About right", "Too much")) +
  labs(x = NULL, y = NULL,
       title = "Averaged support for spending on space exploration") +
  theme_minimal() +
  theme(panel.grid.minor = element_blank())

sp2<-spaceplot+ theme(panel.grid.minor = element_blank(),
      panel.border = element_rect(colour = "black", fill = NA, linewidth = 0.5))

sp2

ggsave("figures/ggplot/spaceplot2.png", plot = sp2)

#Let's look at who believes the Earth goes around the Sun (and vice versa)

table(gss$earthsun)
unique(gss$earthsun)

histogram(~ as.numeric(earthsun), data = gss,
          breaks = c(0.5, 1.5, 2.5),
          scales = list(x = list(at = 1:2,
                                 labels = c("Earth goes around Sun", "Sun goes around Earth"))),
          xlab = "Does the Earth go around the Sun, or the Sun around the Earth?")

gss_earthsun <- gss |>
  mutate(earthsun = as.numeric(earthsun)) |>
  filter(earthsun %in% 1:2) |>
  group_by(year) |>
  summarize(correct = mean(earthsun == 1), n = n())

earthplot<-ggplot(gss_earthsun, aes(x = year, y = correct)) +
  geom_line(linewidth = 1) +
  geom_point(size = 1.5) +
  scale_y_continuous(limits = c(0, 1), labels = scales::percent) +
  labs(x = NULL, y = NULL,
       title = "Share answering that the Earth goes around the Sun") +
  theme_minimal() +
  theme(panel.grid.minor = element_blank())

ep2<-earthplot+ theme(panel.grid.minor = element_blank(),
      panel.border = element_rect(colour = "black", fill = NA, linewidth = 0.5))

ep2

ggsave("figures/ggplot/earthplot2.png", plot = ep2)