Data IO- Data Recoding

Import and Transform religion-income .csv file

library(tidyverse)
## -- Attaching packages --------------------------------------- tidyverse 1.3.1 --
## v ggplot2 3.3.3     v purrr   0.3.4
## v tibble  3.1.1     v dplyr   1.0.6
## v tidyr   1.1.3     v stringr 1.4.0
## v readr   1.4.0     v forcats 0.5.1
## -- Conflicts ------------------------------------------ tidyverse_conflicts() --
## x dplyr::filter() masks stats::filter()
## x dplyr::lag()    masks stats::lag()
library(readxl)
rel_inc <- read_excel("relig-income.xlsx")
rel_inc_long = rel_inc %>%
  rename( 
    religion = `Religious tradition`, 
    n = `Sample Size` 
  ) %>%
  pivot_longer( 
    cols = -c(religion, n),   # all but religion and n 
    names_to = "income",  
    values_to = "proportion" 
  )%>%
  mutate(frequency = round(proportion * n))

Visualize the barplot

library(tidyverse)
rel_inc_long <- rel_inc_long %>%
  mutate(religion = case_when(
    religion == "Evangelical Protestant"           ~ "Ev. Protestant",
    religion == "Historically Black Protestant"    ~ "Hist. Black Protestant",
    religion == 'Unaffiliated (religious "nones")' ~ "Unaffiliated",
    TRUE                                           ~ religion
  ))
rel_inc_long <- rel_inc_long %>%
  mutate(religion = fct_rev(religion))
ggplot(rel_inc_long, aes(y = religion, x = frequency)) +
  geom_col()

Fill barplot with Income

ggplot(rel_inc_long, aes(y = religion, x = frequency,fill= income)) +
  geom_col(position="fill")+
 scale_fill_viridis_d()+
  theme_minimal()

Change theme of plot

ggplot(rel_inc_long, aes(y = religion, x = frequency, fill = income)) +
  geom_col(position = "fill") +
  scale_fill_viridis_d() +
  theme_minimal() +
  theme(legend.position = "bottom")+
    guides(fill = guide_legend(nrow = 2, byrow = TRUE))

ggplot(rel_inc_long, aes(y = religion, x = frequency, fill = income)) +
  geom_col(position = "fill") +
  scale_fill_viridis_d() +
  theme_minimal() +
  theme(legend.position = "bottom") +
  guides(fill = guide_legend(nrow = 2, byrow = TRUE)) +
  labs(
    x = "Proportion", y = "", 
    title = "Income distribution by religious group", 
    subtitle = "Source: Pew Research Center, Religious Landscape Study", 
    fill = "Income" 
    )