Lab5_final

The echo: false option disables the printing of code (only output is displayed).

PART 1: PRACTICE USING PIPES (dplyr) TO SUMMARIZE DATA: TWO CATEGORICAL VARIABLES

library(socviz)
library(dplyr)

Attaching package: 'dplyr'
The following objects are masked from 'package:stats':

    filter, lag
The following objects are masked from 'package:base':

    intersect, setdiff, setequal, union
library(ggplot2)
pip1 <- gss_sm %>%         
  group_by(partyid, marital) %>%
  summarize(N = n()) %>% 
  mutate(freq = N/sum(N),
         pct = round((freq*100),0))
`summarise()` has grouped output by 'partyid'. You can override using the
`.groups` argument.
pip1
# A tibble: 45 × 5
# Groups:   partyid [9]
   partyid          marital           N   freq   pct
   <fct>            <fct>         <int>  <dbl> <dbl>
 1 Strong Democrat  Married         177 0.382     38
 2 Strong Democrat  Widowed          55 0.119     12
 3 Strong Democrat  Divorced         94 0.203     20
 4 Strong Democrat  Separated        20 0.0432     4
 5 Strong Democrat  Never Married   117 0.253     25
 6 Not Str Democrat Married         208 0.419     42
 7 Not Str Democrat Widowed          48 0.0968    10
 8 Not Str Democrat Divorced         65 0.131     13
 9 Not Str Democrat Separated        16 0.0323     3
10 Not Str Democrat Never Married   158 0.319     32
# ℹ 35 more rows
pip1_no_na <- subset(pip1, !is.na(partyid) & !is.na(marital) & !is.na(pct))

# Now plotting with the filtered dataset
ggplot(pip1_no_na, aes(x = partyid, y = pct,caption = "Source: socviz" ,fill = marital)) +
  geom_bar(stat = "identity", position = "dodge") +
  labs(title = "Faceted Horizontal Bar Chart",subtitle = "Widowed status appears to be most prevalent in the Not St Republican category, which could suggest an older demographic within this group" ,x = "Percentage", y = "Party ID") +
  theme(axis.text.x = element_text(angle = 45, hjust = 1))

The data shows that within both Strong Democrats and Not Strong Democrats, the majority of respondents are married, with 38% and 42% respectively. A significant number of Not Strong Democrats have never been married (32%), which is notably higher than the 25% among Strong Democrats. The other categories—widowed, divorced, and separated—are less represented in both groups, suggesting marriage is the predominant status among the surveyed individuals, and there might be variations in political engagement based on marital status.

Part 2

library(ggplot2)

ggplot(pip1_no_na, aes(x = partyid, y = pct, fill = marital)) +
  geom_bar(stat = "identity") +
  labs(title = "Stacked Bar Chart", x = "Party ID", y = "Percentage",caption = "Source: socviz") +
  theme(axis.text.x = element_text(angle = 45, hjust = 1))

Across all party identifications, the majority of individuals are married, taking up more than half of each column. The ‘Never Married’ category is the second most significant segment, particularly among Independent and ‘Ind,near Dem’ groups. The ‘Divorced’ and ‘Widowed’ statuses show smaller proportions across all political affiliations, with the ‘Widowed’ category being the least represented among Strong Republicans and Independents. ‘Separated’ individuals form a relatively minor segment in each group. Interestingly, the proportions of ‘Married’ and ‘Never Married’ individuals seem inversely related across the political spectrum, suggesting varying marital trends among different political party supporters. The chart indicates that while marriage is common across all affiliations, nuances in the other marital statuses may reflect broader social trends within each political group.

ggplot(pip1_no_na, aes(x = reorder(partyid, pct), y = pct, fill = partyid)) + # Reorder for horizontal display
  geom_bar(stat = "identity") +
  facet_wrap(~marital, scales = "free", nrow = 2) + # Create facets for each marital status
  coord_flip() + # Flip coordinates for horizontal bars
  labs(title = "Faceted Horizontal Bar Chart", x = "Party ID", y = "Pct",caption = "Source: socviz") +
  theme(legend.position = "none", axis.text.x = element_text(angle = 45, hjust = 1))

For married individuals, the distribution is fairly even across party lines, with slight variations in percentages. In the widowed category, there appears to be a higher representation among Strong Democrats. Interestingly, the ‘Never Married’ section shows a noticeable leaning towards those identified as Strong Democrat, with comparatively fewer individuals in the Strong Republican category. The ‘Divorced’ category presents a more balanced distribution but with a slightly higher percentage among Independents and those not strongly affiliated with either major party. ‘Separated’ individuals also show a fairly balanced distribution across party identifications. Overall, the chart suggests that while marital status varies across party lines, there are significant political affiliations among the never married and widowed groups.

##Part 3

pip2 <- gss_sm %>%         
  group_by(partyid) %>%
  summarize(N = n(),
            age_mean = mean(age, na.rm=TRUE), 
            sibs_mean = mean(sibs, na.rm=TRUE)) %>% 
  mutate(freq = N/sum(N),
         pct = round((freq*100),0))
pip2
# A tibble: 9 × 6
  partyid                N age_mean sibs_mean   freq   pct
  <fct>              <int>    <dbl>     <dbl>  <dbl> <dbl>
1 Strong Democrat      463     53.8      4.54 0.161     16
2 Not Str Democrat     496     48.1      3.58 0.173     17
3 Ind,near Dem         405     45.2      3.58 0.141     14
4 Independent          473     44.5      4.00 0.165     16
5 Ind,near Rep         292     48.4      3.28 0.102     10
6 Not Str Republican   364     51.3      3.26 0.127     13
7 Strong Republican    270     55.9      3.34 0.0942     9
8 Other Party           72     47.9      3.57 0.0251     3
9 <NA>                  32     47.1      4.26 0.0112     1

The data suggests a correlation between political affiliation and age, with those affiliating as Strong Democrats being older and having more siblings than their counterparts, and Strong Republicans also being older but with a smaller average family size.

##Part 4

library(ggplot2)
highest_age_mean <- max(pip2$age_mean, na.rm = TRUE)

pip2 <- pip2 %>% filter(!is.na(age_mean) & !is.na(sibs_mean))

# Create a scatterplot without plotting NAs
ggplot(pip2, aes(x = age_mean, y = sibs_mean, color = partyid)) +
  geom_point() +  # Add points
  labs(title = "Scatterplot of Age Mean vs. Siblings Mean by Party ID",
       x = "Mean Age",
       y = "Mean Number of siblings",caption = "Source: socviz") +
  theme_minimal() +  # Use a minimal theme
  geom_text(data = subset(pip2, age_mean == highest_age_mean), 
            aes(label = paste("Highest Age Value:", age_mean)), 
            hjust = 1.0, vjust = 0, check_overlap = TRUE)  +
  scale_color_brewer(type = "qual", palette = "Set1")  # Use a qualitative color palette
Warning: Removed 1 rows containing missing values (`geom_point()`).

Graph annotations are showing the points that are older than 45 with less than 2 kids

The graph reveals several trends: Strong Democrats tend to be the oldest with the largest number of siblings, as indicated by their position in the top right, suggesting a trend of larger family sizes among older demographics within this political group. Strong Republicans also appear older on average but with fewer siblings than Strong Democrats, positioned in the bottom right. Independents and those near Democrats (Ind,near Dem) have a moderate number of siblings and are younger on average. Not Str Democrats, Ind,near Rep, and Not Str Republicans are clustered in the center, indicating a middle ground in both age and sibling count. The data generally shows that those with stronger political affiliations (either Democrat or Republican) are older, with varying family sizes, while those with weaker or no stated affiliations tend to be younger, with a slight tendency towards smaller families.

##Part 5

highest_age_mean <- max(pip2$age_mean, na.rm = TRUE)

ggplot(pip2, aes(x = age_mean, y = sibs_mean, color = partyid)) +
  geom_point() +  
  labs(title = "Mean Age vs. Mean Number of Siblings by Party ID",
       x = "Mean Age",
       y = "Mean Number of Siblings",
       caption = "Source: socviz",
       color = "Party ID") +  
  theme_minimal() +  
  theme(legend.title = element_text(face = "bold", size = 12),  
        legend.position = "right",  
        legend.box = "vertical") +  
  scale_color_brewer(type = "qual", palette = "Set1", direction = -1) +  
  geom_text(data = subset(pip2, age_mean == highest_age_mean), 
            aes(label = paste("Highest Age Value:", age_mean)), 
            hjust = 1.0, vjust = 0, check_overlap = TRUE) +  
  guides(color = guide_legend(title = "Party ID", title.position = "top", label.position = "right", 
                              title.hjust = 0.5, label.hjust = 0.5))
Warning: Removed 1 rows containing missing values (`geom_point()`).

Graph annotations are showing the points that are older than 45 with less than 2 kids

The graph reveals several trends: Strong Democrats tend to be the oldest with the largest number of siblings, as indicated by their position in the top right, suggesting a trend of larger family sizes among older demographics within this political group. Strong Republicans also appear older on average but with fewer siblings than Strong Democrats, positioned in the bottom right. Independents and those near Democrats (Ind,near Dem) have a moderate number of siblings and are younger on average. Not Str Democrats, Ind,near Rep, and Not Str Republicans are clustered in the center, indicating a middle ground in both age and sibling count. The data generally shows that those with stronger political affiliations (either Democrat or Republican) are older, with varying family sizes, while those with weaker or no stated affiliations tend to be younger, with a slight tendency towards smaller families.

##Part 6

library(ggplot2)
ggplot(pip2, aes(x = age_mean, y = sibs_mean, label = partyid)) +
  geom_point(aes(color = partyid)) +  # Add scatterplot points
  geom_text(nudge_x = 0.5, nudge_y = 0.5, check_overlap = TRUE) +  # Add data labels
  labs(title = "Mean Age vs. Mean Number of Siblings by Party ID",
       subtitle = "Data shows family sizes across political affiliations with significant differences in mean age",
       x = "Mean Age",
       y = "Mean Number of Siblings",
       caption = "Source: socviz") +  # Add source in the caption
  theme_minimal() +  # Use a minimal theme for a clean appearance
  scale_color_brewer(type = "qual", palette = "Set1") +  # Apply color palette
  theme(legend.position = "none")  # Remove the legend
Warning: Removed 1 rows containing missing values (`geom_point()`).
Warning: Removed 1 rows containing missing values (`geom_text()`).

The graph reveals several trends: Strong Democrats tend to be the oldest with the largest number of siblings, as indicated by their position in the top right, suggesting a trend of larger family sizes among older demographics within this political group. Strong Republicans also appear older on average but with fewer siblings than Strong Democrats, positioned in the bottom right. Independents and those near Democrats (Ind,near Dem) have a moderate number of siblings and are younger on average. Not Str Democrats, Ind,near Rep, and Not Str Republicans are clustered in the center, indicating a middle ground in both age and sibling count. The data generally shows that those with stronger political affiliations (either Democrat or Republican) are older, with varying family sizes, while those with weaker or no stated affiliations tend to be younger, with a slight tendency towards smaller families.