diff --git a/docs/Hacking-Religion--TRS---Data-Science-in-Action.pdf b/docs/Hacking-Religion--TRS---Data-Science-in-Action.pdf index b78c2b6..37bf32a 100644 Binary files a/docs/Hacking-Religion--TRS---Data-Science-in-Action.pdf and b/docs/Hacking-Religion--TRS---Data-Science-in-Action.pdf differ diff --git a/docs/chapter_1.html b/docs/chapter_1.html index 6530475..c393883 100644 --- a/docs/chapter_1.html +++ b/docs/chapter_1.html @@ -572,7 +572,7 @@ div.csl-indent {
2
-We’ll re-order the column by size. +We’ll re-order the column by size.
@@ -595,19 +595,19 @@ div.csl-indent {
1
-First, remove the column with region names and the totals for the regions as we want just integer data. +First, remove the column with region names and the totals for the regions as we want just integer data.
2
-Second calculate the totals. In this example we use the tidyverse library dplyr(), but you can also do this using base R with colsums() like this: uk_census_2021_religion_totals <- colSums(uk_census_2021_religion_totals, na.rm = TRUE). The downside with base R is that you’ll also need to convert the result into a dataframe for ggplot like this: uk_census_2021_religion_totals <- as.data.frame(uk_census_2021_religion_totals) +Second calculate the totals. In this example we use the tidyverse library dplyr(), but you can also do this using base R with colsums() like this: uk_census_2021_religion_totals <- colSums(uk_census_2021_religion_totals, na.rm = TRUE). The downside with base R is that you’ll also need to convert the result into a dataframe for ggplot like this: uk_census_2021_religion_totals <- as.data.frame(uk_census_2021_religion_totals)
3
-In order to visualise this data using ggplot, we need to shift this data from wide to long format. This is a quick job using gather() +In order to visualise this data using ggplot, we need to shift this data from wide to long format. This is a quick job using gather()
4
-Now plot it out and have a look! +Now plot it out and have a look!
diff --git a/docs/chapter_2.html b/docs/chapter_2.html index e10c7af..6e351b4 100644 --- a/docs/chapter_2.html +++ b/docs/chapter_2.html @@ -336,15 +336,15 @@ So Who’s Religious?
1
-First we generate new a dataframe with sums per category and +First we generate new a dataframe with sums per category and
2
-…sort in descending order +…sort in descending order
3
-Then we add new column with percentages based on the sums you’ve just generated +Then we add new column with percentages based on the sums you’ve just generated
@@ -413,25 +413,36 @@ So Who’s Religious?
1
-Note: we have removed sort = TRUE in the above statement as it will enforce sorting the data by quantities rather than the factor order. It wouldn’t really make sense to plot this chart in the order of response. +Note: we have removed sort = TRUE in the above statement as it will enforce sorting the data by quantities rather than the factor order. It wouldn’t really make sense to plot this chart in the order of response.

Now, let’s plot that data:

-
caption <- "Respondent Religiosity"
+
caption <- "Respondent Religiosity"
 ggplot(religiosity_sums, aes(x = response, y = n, color=response)) +
-  geom_col(colour = "white", aes(fill = response)) +
+1  geom_col(colour = "white", aes(fill = response)) +
   ## get rid of all elements except y axis labels + adjust plot margin
-  coord_flip() +
+2  coord_flip() +
   theme(plot.margin = margin(rep(15, 4))) +
-  labs(caption = caption)
+ labs(caption = caption)
+
+
+
1
+
+We’ve added colors, because colours are fun. +
+
2
+
+Also new here is coord_flip to rotate the chart so we have bars going horizontally +
+
+

-

We’ve added a few elements here: 1. Colors, because colours are fun. 2. coord_flip to rotate the chart so we have bars going horizontally

Since we’re thinking about how things look just now, let’s play with themes for a minute. ggplot is a really powerful tool for visualising information, but it also has some quite nice features for making things look pretty.

If you’d like to take a proper deep dive on all this theme stuff, R-Charts has a great set of examples showing you how a number of different theme packages look in practice, “R-Charts on Themes”.

R has a number of built-in themes, but these are mostly driven by functional concerns, such as whether you might want to print your chart or have a less heavy look overall. So for example you might use theme_light() in the following way:

@@ -479,8 +490,10 @@ So Who’s Religious? # Spirituality scale -# stat_summary(climate_experience_data$Q52_score) -mean(climate_experience_data$Q52_score) +# JK note to self: need to fix stat_summary plot here + +# stat_summary(climate_experience_data$Q52_score) +mean(climate_experience_data$Q52_score)
[1] 6.047454
diff --git a/docs/chapter_2_files/figure-html/unnamed-chunk-14-1.png b/docs/chapter_2_files/figure-html/unnamed-chunk-14-1.png index f43b5a1..b4294c6 100644 Binary files a/docs/chapter_2_files/figure-html/unnamed-chunk-14-1.png and b/docs/chapter_2_files/figure-html/unnamed-chunk-14-1.png differ diff --git a/docs/chapter_2_files/figure-html/unnamed-chunk-15-1.png b/docs/chapter_2_files/figure-html/unnamed-chunk-15-1.png index 488a769..12e3d8d 100644 Binary files a/docs/chapter_2_files/figure-html/unnamed-chunk-15-1.png and b/docs/chapter_2_files/figure-html/unnamed-chunk-15-1.png differ diff --git a/docs/search.json b/docs/search.json index 1cd97f7..66cb7ae 100644 --- a/docs/search.json +++ b/docs/search.json @@ -109,7 +109,7 @@ "href": "chapter_2.html#working-with-a-continum-religiosity-and-spirituality", "title": "2  Survey Data: Spotlight Project", "section": "2.4 Working With a Continum: Religiosity and Spirituality", - "text": "2.4 Working With a Continum: Religiosity and Spirituality\nSo far we’ve just worked with bar plots, but there are a lot of other possible visualisations and types of data which demand them.\nAs I’ve mentioned above, on this survey we also asked respondents to tell us on by rating themselves on a scale of 0-10 with 0 being “not religious at all” and 10 being “very religious” in response to the question, “Regardless of whether you belong to a particular religion, how religious would you say you are?”\nWe’ll recycle some code from our previous import to bring in the Q57 data:\n\nreligiosity <- as_tibble(as_factor(climate_experience_data$Q57_1))\nnames(religiosity) <- c(\"response\")\nreligiosity <- filter(religiosity, !is.na(response))\nreligiosity_sums <- religiosity %>% \n1 dplyr::count(response) %>%\n dplyr::mutate(response = forcats::fct_rev(forcats::fct_inorder(response)))\nreligiosity_sums <- religiosity_sums %>% \n dplyr::mutate(perc = scales::percent(n / sum(n), accuracy = .1, trim = FALSE))\n\n\n1\n\nNote: we have removed sort = TRUE in the above statement as it will enforce sorting the data by quantities rather than the factor order. It wouldn’t really make sense to plot this chart in the order of response.\n\n\n\n\nNow, let’s plot that data:\n\ncaption <- \"Respondent Religiosity\"\nggplot(religiosity_sums, aes(x = response, y = n, color=response)) +\n geom_col(colour = \"white\", aes(fill = response)) +\n ## get rid of all elements except y axis labels + adjust plot margin\n coord_flip() +\n theme(plot.margin = margin(rep(15, 4))) +\n labs(caption = caption)\n\n\n\n\nWe’ve added a few elements here: 1. Colors, because colours are fun. 2. coord_flip to rotate the chart so we have bars going horizontally\nSince we’re thinking about how things look just now, let’s play with themes for a minute. ggplot is a really powerful tool for visualising information, but it also has some quite nice features for making things look pretty.\nIf you’d like to take a proper deep dive on all this theme stuff, R-Charts has a great set of examples showing you how a number of different theme packages look in practice, “R-Charts on Themes”.\nR has a number of built-in themes, but these are mostly driven by functional concerns, such as whether you might want to print your chart or have a less heavy look overall. So for example you might use theme_light() in the following way:\n\nggplot(religiosity_sums, aes(x = response, y = n, color=response)) +\n geom_col(colour = \"white\", aes(fill = response)) +\n ## get rid of all elements except y axis labels + adjust plot margin\n coord_flip() +\n theme(plot.margin = margin(rep(15, 4))) +\n labs(caption = caption) +\n theme_light()\n\n\n\n\nYou can also use additional packages like ggthemes() or hrbrthemes() so for example we might want to try the pander theme which has it’s own special (and very cheerful) colour palette.\n\nlibrary(ggthemes) |> suppressPackageStartupMessages()\nggplot(religiosity_sums, aes(x = response, y = n, color=response)) + geom_col(colour = \"white\", aes(fill = response)) + coord_flip() + theme(plot.margin = margin(rep(15, 4))) + labs(caption = caption) + \n theme_pander() +\n scale_fill_pander()\n\n\n\n\nOr, you might try the well-crafted typgraphy from hbrthemes in the theme_ipsum_pub theme:\n\nlibrary(hrbrthemes) |> suppressPackageStartupMessages()\nggplot(religiosity_sums, aes(x = response, y = n, color=response)) + geom_col(colour = \"white\", aes(fill = response)) + coord_flip() + theme(plot.margin = margin(rep(15, 4))) + labs(caption = caption) + \n theme_ipsum_pub() +\n scale_fill_pander()\n\n\n\n\nWe’re going to come back to this chart, but let’s set it to one side for a moment and build up a visualisation of the spirituality scale data. The spirituality scale questions come from research by ___ and ___. These researchers developed a series of questions which they asked respondents in a survey. The advantage here is that you’re getting at the question of spirituality from a lot of different angles, and then you combine the scores from all the questions to get a mean “spirituality score”.\n\n### Spirituality scale --------------------------------------------------------------\n# Calculate overall mean spirituality score based on six questions:\nclimate_experience_data$Q52_score <- rowMeans(select(climate_experience_data, Q52a_1:Q52f_1))\n\nLike we did in chapter 1, let’s start by exploring the data and get a bit of a sense of the character of the responses overall. One good place to start is to find out the mean response for our two continum questions:\n\n# t_testing and means\n\n# Spirituality scale\n\n# stat_summary(climate_experience_data$Q52_score)\nmean(climate_experience_data$Q52_score)\n\n[1] 6.047454\n\n# Q57 Regardless of whether you belong to a particular religion, how religious would you say you are?\n# 0-10, Not religious at all => Very religious; mean=5.58\n\nmean(climate_experience_data$Q57_1) # religiosity\n\n[1] 5.581349\n\n# Q58 Apart from weddings, funerals and other special occasions, how often do you attend religious services?\n# coded at 1-5, lower value = stronger mean=3.439484\n\nmean(climate_experience_data$Q58) # service attendance\n\n[1] 3.439484\n\n# Q59 Apart from when you are at religious services, how often do you pray?\n# coded at 1-5, lower = stronger mean=2.50496\n\nmean(climate_experience_data$Q59)\n\n[1] 2.50496\n\n\nNow let’s try out some visualisations:\n\n## Q52 Spirituality data ------------------------\n\nq52_data <- select(climate_experience_data, Q52a_1:Q52f_1)\n# Data is at wide format, we need to make it 'tidy' or 'long'\nq52_data <- q52_data %>% \n gather(key=\"text\", value=\"value\") %>%\n # rename columns\n mutate(text = gsub(\"Q52_\", \"\",text, ignore.case = TRUE)) %>%\n mutate(value = round(as.numeric(value),0))\n\nWarning: attributes are not identical across measure variables; they will be\ndropped\n\n# Change names of rows to question text\nq52_data <- q52_data %>% \n gather(key=\"text\", value=\"value\") %>%\n # rename columns\n mutate(text = gsub(\"Q52a_1\", \"In terms of questions I have about my life, my spirituality answers...\",text, ignore.case = TRUE)) %>%\n mutate(text = gsub(\"Q52b_1\", \"Growing spiritually is important...\",text, ignore.case = TRUE)) %>%\n mutate(text = gsub(\"Q52c_1\", \"When I<e2><80><99>m faced with an important decision, spirituality plays a role...\",text, ignore.case = TRUE)) %>%\n mutate(text = gsub(\"Q52d_1\", \"Spirituality is part of my life...\",text, ignore.case = TRUE)) %>%\n mutate(text = gsub(\"Q52e_1\", \"When I think of things that help me grow and mature as a person, spirituality has an effect on my personal growth...\",text, ignore.case = TRUE)) %>%\n mutate(text = gsub(\"Q52f_1\", \"My spiritual beliefs affect aspects of my life...\",text, ignore.case = TRUE))\n\n# Plot\n# Used for gradient colour schemes, as with violin plots\nlibrary(viridis) \n\nLoading required package: viridisLite\n\nq52_plot <- q52_data %>%\n mutate(text = fct_reorder(text, value)) %>% # Reorder data\n ggplot( aes(x=text, y=value, fill=text, color=text)) +\n geom_boxplot() +\n scale_fill_viridis(discrete=TRUE, alpha=0.8) +\n geom_jitter(color=\"black\", size=0.2, alpha=0.2) +\n theme_ipsum() +\n theme(legend.position=\"none\", axis.text.y = element_text(size = 8)) +\n coord_flip() + # This switch X and Y axis and allows to get the horizontal version\n xlab(\"\") +\n ylab(\"Spirituality scales\") +\n scale_x_discrete(labels = function(x) str_wrap(x, width = 45))\n\n# using gridExtra to specify explicit dimensions for printing\nq52_plot\n\n\n\nggsave(\"figures/q52_boxplot.png\", width = 20, height = 10, units = \"cm\")\n\nThere’s an enhanced version of this plot we can use, called ggstatsplot() to get a different view:\n\n# As an alternative trying ggstatsplot:\nlibrary(rstantools)\n\nThis is rstantools version 2.3.1.1\n\nlibrary(ggstatsplot)\n\nYou can cite this package as:\n Patil, I. (2021). Visualizations with statistical details: The 'ggstatsplot' approach.\n Journal of Open Source Software, 6(61), 3167, doi:10.21105/joss.03167\n\nq52_plot_alt <- ggbetweenstats(\n data = q52_data,\n x = text,\n y = value,\n outlier.tagging = TRUE,\n title = \"Intrinsic Spirituality Scale Responses\"\n) +\n scale_x_discrete(labels = function(x) str_wrap(x, width = 30)) +\n # Customizations\n theme(\n # Change fonts in the plot\n text = element_text(family = \"Helvetica\", size = 8, color = \"black\"),\n plot.title = element_text(\n family = \"Abril Fatface\", \n size = 20,\n face = \"bold\",\n color = \"#2a475e\"\n ),\n # Statistical annotations below the main title\n plot.subtitle = element_text(\n family = \"Helvetica\", \n size = 12, \n face = \"bold\",\n color=\"#1b2838\"\n ),\n plot.title.position = \"plot\", # slightly different from default\n axis.text = element_text(size = 10, color = \"black\"),\n axis.text.x = element_text(size = 7),\n axis.title = element_text(size = 12),\n axis.line = element_line(colour = \"grey50\"),\n panel.grid.minor = element_blank(),\n panel.grid.major.x = element_blank(),\n panel.grid = element_line(color = \"#b4aea9\"),\n panel.grid.major.y = element_line(linetype = \"dashed\"),\n panel.background = element_rect(fill = \"#fbf9f4\", color = \"#fbf9f4\"),\n plot.background = element_rect(fill = \"#fbf9f4\", color = \"#fbf9f4\")\n )\n\nScale for x is already present.\nAdding another scale for x, which will replace the existing scale.\n\nq52_plot_alt\n\n\n\nggsave(\"figures/q52_plot_alt.png\", width = 20, height = 12, units = \"cm\")\n\nOne thing that might be interesting to test here is whether spirituality and religiosity are similar for our respondents.\n\nggplot(climate_experience_data, aes(x=Q52_score, y=Q57_1)) + labs(x=\"Spirituality Scale Score\", y = \"How Religious?\") +\n geom_point(size=1, alpha=0.3) + geom_smooth(method=\"auto\", se=TRUE, fullrange=FALSE, level=0.95)\n\n`geom_smooth()` using method = 'gam' and formula = 'y ~ s(x, bs = \"cs\")'\n\n\n\n\n# using http://sthda.com/english/wiki/ggplot2-scatter-plots-quick-start-guide-r-software-and-data-visualization\n\nggplot(climate_experience_data, aes(x=Q52_score, y=Q57_1)) +\n labs(x=\"Spirituality Scale Score\", y = \"How Religious?\") +\n geom_point(size=1, alpha=0.3) + stat_density_2d(aes(fill = ..level..), geom=\"polygon\", alpha=0.3)+\n scale_fill_gradient(low=\"blue\", high=\"red\") +\n theme_minimal()\n\nWarning: The dot-dot notation (`..level..`) was deprecated in ggplot2 3.4.0.\ni Please use `after_stat(level)` instead.\n\n\n\n\n\nBecause the responses to these two questions, about spirituality and religiosity are on a continuum, we can also use them, like we did in previous charts, to subset other datasets. A simple way of doing this is to separate our respondents into “high,” “medium,” and “low” bins for the two questions. Rather than working with hard values, like assigning 0-3, 4-6 and 7-10 for low medium and high, we’ll work with the range of values that respondents actually chose. This is particularly appropriate as the median answer to these questions was not “5”. So we’ll use the statistical concept of standard deviation, which R can calculate almost magically for us, in the following way:\n\n# Create low/med/high bins based on Mean and +1/-1 Standard Deviation\nclimate_experience_data <- climate_experience_data %>%\n mutate(\n Q52_bin = case_when(\n Q52_score > mean(Q52_score) + sd(Q52_score) ~ \"high\",\n Q52_score < mean(Q52_score) - sd(Q52_score) ~ \"low\",\n TRUE ~ \"medium\"\n ) %>% factor(levels = c(\"low\", \"medium\", \"high\"))\n )\n\n\n## Q57 subsetting based on Religiosity --------------------------------------------------------------\nclimate_experience_data <- climate_experience_data %>%\n mutate(\n Q57_bin = case_when(\n Q57_1 > mean(Q57_1) + sd(Q57_1) ~ \"high\",\n Q57_1 < mean(Q57_1) - sd(Q57_1) ~ \"low\",\n TRUE ~ \"medium\"\n ) %>% factor(levels = c(\"low\", \"medium\", \"high\"))\n )\n\nAs in the previous chapter, it’s useful to explore multiple factors when possible. So I’d like us to take the data about political affiliation to visualise alongside our religion and spirituality data. this will help us to see where effects are more or less significant and give us a point of comparison.\n\n## Q53 subsetting based on Political LR orientation --------------------------------------------------------------\n# Generate low/med/high bins based on Mean and SD\nclimate_experience_data <- climate_experience_data %>%\n mutate(\n Q53_bin = case_when(\n Q53_1 > mean(Q53_1) + sd(Q53_1) ~ \"high\",\n Q53_1 < mean(Q53_1) - sd(Q53_1) ~ \"low\",\n TRUE ~ \"medium\"\n ) %>% factor(levels = c(\"low\", \"medium\", \"high\"))\n )\n\nNow let’s use those bins to explore some of the responses about attitudes towards climate change:\n\n# Faceted plot working with 3x3 grid\ndf <- select(climate_experience_data, Q52_bin, Q53_bin, Q57_bin, Q58)\nnames(df) <- c(\"Q52_bin\", \"Q53_bin\", \"Q57_bin\", \"response\")\nfacet_names <- c(`Q52_bin` = \"Spirituality\", `Q53_bin` = \"Politics L/R\", `Q57_bin` = \"Religiosity\", `low`=\"low\", `medium`=\"medium\", `high`=\"high\")\nfacet_labeller <- function(variable,value){return(facet_names[value])}\ndf$response <- factor(df$response, ordered = TRUE, levels = c(\"1\", \"2\", \"3\", \"4\", \"5\"))\ndf$response <- fct_recode(df$response, \"More than once a week\" = \"1\", \"Once a week\" = \"2\", \"At least once a month\" = \"3\", \"Only on special holy days\" = \"4\", \"Never\" = \"5\")\ndf %>% \n # we need to get the data including facet info in long format, so we use pivot_longer()\n pivot_longer(!response, names_to = \"bin_name\", values_to = \"b\") %>% \n # add counts for plot below\n count(response, bin_name, b) %>%\n group_by(bin_name,b) %>%\n mutate(perc=paste0(round(n*100/sum(n),1),\"%\")) %>% \n # run ggplot\n ggplot(aes(x = n, y = \"\", fill = response)) +\n geom_col(position=position_fill(), aes(fill=response)) +\n geom_text(aes(label = perc), position = position_fill(vjust=.5), size=2) +\n scale_fill_brewer(palette = \"Dark2\", type = \"qual\") +\n scale_x_continuous(labels = scales::percent_format()) +\n facet_grid(vars(b), vars(bin_name), labeller=as_labeller(facet_names)) + \n labs(caption = caption, x = \"\", y = \"\") + \n guides(fill = guide_legend(title = NULL))\n\n\n\nggsave(\"figures/q58_faceted.png\", width = 30, height = 10, units = \"cm\")\n\n\n\n\n\n\n\n\n\nWhat is Religion?\n\n\n\nContent tbd\n\n\n\n\n\n\n\n\nHybrid Religious Identity\n\n\n\nContent tbd\n\n\n\n\n\n\n\n\nWhat is Secularisation?\n\n\n\nContent tbd" + "text": "2.4 Working With a Continum: Religiosity and Spirituality\nSo far we’ve just worked with bar plots, but there are a lot of other possible visualisations and types of data which demand them.\nAs I’ve mentioned above, on this survey we also asked respondents to tell us on by rating themselves on a scale of 0-10 with 0 being “not religious at all” and 10 being “very religious” in response to the question, “Regardless of whether you belong to a particular religion, how religious would you say you are?”\nWe’ll recycle some code from our previous import to bring in the Q57 data:\n\nreligiosity <- as_tibble(as_factor(climate_experience_data$Q57_1))\nnames(religiosity) <- c(\"response\")\nreligiosity <- filter(religiosity, !is.na(response))\nreligiosity_sums <- religiosity %>% \n1 dplyr::count(response) %>%\n dplyr::mutate(response = forcats::fct_rev(forcats::fct_inorder(response)))\nreligiosity_sums <- religiosity_sums %>% \n dplyr::mutate(perc = scales::percent(n / sum(n), accuracy = .1, trim = FALSE))\n\n\n1\n\nNote: we have removed sort = TRUE in the above statement as it will enforce sorting the data by quantities rather than the factor order. It wouldn’t really make sense to plot this chart in the order of response.\n\n\n\n\nNow, let’s plot that data:\n\ncaption <- \"Respondent Religiosity\"\nggplot(religiosity_sums, aes(x = response, y = n, color=response)) +\n1 geom_col(colour = \"white\", aes(fill = response)) +\n ## get rid of all elements except y axis labels + adjust plot margin\n2 coord_flip() +\n theme(plot.margin = margin(rep(15, 4))) +\n labs(caption = caption)\n\n\n1\n\nWe’ve added colors, because colours are fun.\n\n2\n\nAlso new here is coord_flip to rotate the chart so we have bars going horizontally\n\n\n\n\n\n\n\nSince we’re thinking about how things look just now, let’s play with themes for a minute. ggplot is a really powerful tool for visualising information, but it also has some quite nice features for making things look pretty.\nIf you’d like to take a proper deep dive on all this theme stuff, R-Charts has a great set of examples showing you how a number of different theme packages look in practice, “R-Charts on Themes”.\nR has a number of built-in themes, but these are mostly driven by functional concerns, such as whether you might want to print your chart or have a less heavy look overall. So for example you might use theme_light() in the following way:\n\nggplot(religiosity_sums, aes(x = response, y = n, color=response)) +\n geom_col(colour = \"white\", aes(fill = response)) +\n ## get rid of all elements except y axis labels + adjust plot margin\n coord_flip() +\n theme(plot.margin = margin(rep(15, 4))) +\n labs(caption = caption) +\n theme_light()\n\n\n\n\nYou can also use additional packages like ggthemes() or hrbrthemes() so for example we might want to try the pander theme which has it’s own special (and very cheerful) colour palette.\n\nlibrary(ggthemes) |> suppressPackageStartupMessages()\nggplot(religiosity_sums, aes(x = response, y = n, color=response)) + geom_col(colour = \"white\", aes(fill = response)) + coord_flip() + theme(plot.margin = margin(rep(15, 4))) + labs(caption = caption) + \n theme_pander() +\n scale_fill_pander()\n\n\n\n\nOr, you might try the well-crafted typgraphy from hbrthemes in the theme_ipsum_pub theme:\n\nlibrary(hrbrthemes) |> suppressPackageStartupMessages()\nggplot(religiosity_sums, aes(x = response, y = n, color=response)) + geom_col(colour = \"white\", aes(fill = response)) + coord_flip() + theme(plot.margin = margin(rep(15, 4))) + labs(caption = caption) + \n theme_ipsum_pub() +\n scale_fill_pander()\n\n\n\n\nWe’re going to come back to this chart, but let’s set it to one side for a moment and build up a visualisation of the spirituality scale data. The spirituality scale questions come from research by ___ and ___. These researchers developed a series of questions which they asked respondents in a survey. The advantage here is that you’re getting at the question of spirituality from a lot of different angles, and then you combine the scores from all the questions to get a mean “spirituality score”.\n\n### Spirituality scale --------------------------------------------------------------\n# Calculate overall mean spirituality score based on six questions:\nclimate_experience_data$Q52_score <- rowMeans(select(climate_experience_data, Q52a_1:Q52f_1))\n\nLike we did in chapter 1, let’s start by exploring the data and get a bit of a sense of the character of the responses overall. One good place to start is to find out the mean response for our two continum questions:\n\n# t_testing and means\n\n# Spirituality scale\n\n# JK note to self: need to fix stat_summary plot here\n\n# stat_summary(climate_experience_data$Q52_score)\nmean(climate_experience_data$Q52_score)\n\n[1] 6.047454\n\n# Q57 Regardless of whether you belong to a particular religion, how religious would you say you are?\n# 0-10, Not religious at all => Very religious; mean=5.58\n\nmean(climate_experience_data$Q57_1) # religiosity\n\n[1] 5.581349\n\n# Q58 Apart from weddings, funerals and other special occasions, how often do you attend religious services?\n# coded at 1-5, lower value = stronger mean=3.439484\n\nmean(climate_experience_data$Q58) # service attendance\n\n[1] 3.439484\n\n# Q59 Apart from when you are at religious services, how often do you pray?\n# coded at 1-5, lower = stronger mean=2.50496\n\nmean(climate_experience_data$Q59)\n\n[1] 2.50496\n\n\nNow let’s try out some visualisations:\n\n## Q52 Spirituality data ------------------------\n\nq52_data <- select(climate_experience_data, Q52a_1:Q52f_1)\n# Data is at wide format, we need to make it 'tidy' or 'long'\nq52_data <- q52_data %>% \n gather(key=\"text\", value=\"value\") %>%\n # rename columns\n mutate(text = gsub(\"Q52_\", \"\",text, ignore.case = TRUE)) %>%\n mutate(value = round(as.numeric(value),0))\n\nWarning: attributes are not identical across measure variables; they will be\ndropped\n\n# Change names of rows to question text\nq52_data <- q52_data %>% \n gather(key=\"text\", value=\"value\") %>%\n # rename columns\n mutate(text = gsub(\"Q52a_1\", \"In terms of questions I have about my life, my spirituality answers...\",text, ignore.case = TRUE)) %>%\n mutate(text = gsub(\"Q52b_1\", \"Growing spiritually is important...\",text, ignore.case = TRUE)) %>%\n mutate(text = gsub(\"Q52c_1\", \"When I<e2><80><99>m faced with an important decision, spirituality plays a role...\",text, ignore.case = TRUE)) %>%\n mutate(text = gsub(\"Q52d_1\", \"Spirituality is part of my life...\",text, ignore.case = TRUE)) %>%\n mutate(text = gsub(\"Q52e_1\", \"When I think of things that help me grow and mature as a person, spirituality has an effect on my personal growth...\",text, ignore.case = TRUE)) %>%\n mutate(text = gsub(\"Q52f_1\", \"My spiritual beliefs affect aspects of my life...\",text, ignore.case = TRUE))\n\n# Plot\n# Used for gradient colour schemes, as with violin plots\nlibrary(viridis) \n\nLoading required package: viridisLite\n\nq52_plot <- q52_data %>%\n mutate(text = fct_reorder(text, value)) %>% # Reorder data\n ggplot( aes(x=text, y=value, fill=text, color=text)) +\n geom_boxplot() +\n scale_fill_viridis(discrete=TRUE, alpha=0.8) +\n geom_jitter(color=\"black\", size=0.2, alpha=0.2) +\n theme_ipsum() +\n theme(legend.position=\"none\", axis.text.y = element_text(size = 8)) +\n coord_flip() + # This switch X and Y axis and allows to get the horizontal version\n xlab(\"\") +\n ylab(\"Spirituality scales\") +\n scale_x_discrete(labels = function(x) str_wrap(x, width = 45))\n\n# using gridExtra to specify explicit dimensions for printing\nq52_plot\n\n\n\nggsave(\"figures/q52_boxplot.png\", width = 20, height = 10, units = \"cm\")\n\nThere’s an enhanced version of this plot we can use, called ggstatsplot() to get a different view:\n\n# As an alternative trying ggstatsplot:\nlibrary(rstantools)\n\nThis is rstantools version 2.3.1.1\n\nlibrary(ggstatsplot)\n\nYou can cite this package as:\n Patil, I. (2021). Visualizations with statistical details: The 'ggstatsplot' approach.\n Journal of Open Source Software, 6(61), 3167, doi:10.21105/joss.03167\n\nq52_plot_alt <- ggbetweenstats(\n data = q52_data,\n x = text,\n y = value,\n outlier.tagging = TRUE,\n title = \"Intrinsic Spirituality Scale Responses\"\n) +\n scale_x_discrete(labels = function(x) str_wrap(x, width = 30)) +\n # Customizations\n theme(\n # Change fonts in the plot\n text = element_text(family = \"Helvetica\", size = 8, color = \"black\"),\n plot.title = element_text(\n family = \"Abril Fatface\", \n size = 20,\n face = \"bold\",\n color = \"#2a475e\"\n ),\n # Statistical annotations below the main title\n plot.subtitle = element_text(\n family = \"Helvetica\", \n size = 12, \n face = \"bold\",\n color=\"#1b2838\"\n ),\n plot.title.position = \"plot\", # slightly different from default\n axis.text = element_text(size = 10, color = \"black\"),\n axis.text.x = element_text(size = 7),\n axis.title = element_text(size = 12),\n axis.line = element_line(colour = \"grey50\"),\n panel.grid.minor = element_blank(),\n panel.grid.major.x = element_blank(),\n panel.grid = element_line(color = \"#b4aea9\"),\n panel.grid.major.y = element_line(linetype = \"dashed\"),\n panel.background = element_rect(fill = \"#fbf9f4\", color = \"#fbf9f4\"),\n plot.background = element_rect(fill = \"#fbf9f4\", color = \"#fbf9f4\")\n )\n\nScale for x is already present.\nAdding another scale for x, which will replace the existing scale.\n\nq52_plot_alt\n\n\n\nggsave(\"figures/q52_plot_alt.png\", width = 20, height = 12, units = \"cm\")\n\nOne thing that might be interesting to test here is whether spirituality and religiosity are similar for our respondents.\n\nggplot(climate_experience_data, aes(x=Q52_score, y=Q57_1)) + labs(x=\"Spirituality Scale Score\", y = \"How Religious?\") +\n geom_point(size=1, alpha=0.3) + geom_smooth(method=\"auto\", se=TRUE, fullrange=FALSE, level=0.95)\n\n`geom_smooth()` using method = 'gam' and formula = 'y ~ s(x, bs = \"cs\")'\n\n\n\n\n# using http://sthda.com/english/wiki/ggplot2-scatter-plots-quick-start-guide-r-software-and-data-visualization\n\nggplot(climate_experience_data, aes(x=Q52_score, y=Q57_1)) +\n labs(x=\"Spirituality Scale Score\", y = \"How Religious?\") +\n geom_point(size=1, alpha=0.3) + stat_density_2d(aes(fill = ..level..), geom=\"polygon\", alpha=0.3)+\n scale_fill_gradient(low=\"blue\", high=\"red\") +\n theme_minimal()\n\nWarning: The dot-dot notation (`..level..`) was deprecated in ggplot2 3.4.0.\ni Please use `after_stat(level)` instead.\n\n\n\n\n\nBecause the responses to these two questions, about spirituality and religiosity are on a continuum, we can also use them, like we did in previous charts, to subset other datasets. A simple way of doing this is to separate our respondents into “high,” “medium,” and “low” bins for the two questions. Rather than working with hard values, like assigning 0-3, 4-6 and 7-10 for low medium and high, we’ll work with the range of values that respondents actually chose. This is particularly appropriate as the median answer to these questions was not “5”. So we’ll use the statistical concept of standard deviation, which R can calculate almost magically for us, in the following way:\n\n# Create low/med/high bins based on Mean and +1/-1 Standard Deviation\nclimate_experience_data <- climate_experience_data %>%\n mutate(\n Q52_bin = case_when(\n Q52_score > mean(Q52_score) + sd(Q52_score) ~ \"high\",\n Q52_score < mean(Q52_score) - sd(Q52_score) ~ \"low\",\n TRUE ~ \"medium\"\n ) %>% factor(levels = c(\"low\", \"medium\", \"high\"))\n )\n\n\n## Q57 subsetting based on Religiosity --------------------------------------------------------------\nclimate_experience_data <- climate_experience_data %>%\n mutate(\n Q57_bin = case_when(\n Q57_1 > mean(Q57_1) + sd(Q57_1) ~ \"high\",\n Q57_1 < mean(Q57_1) - sd(Q57_1) ~ \"low\",\n TRUE ~ \"medium\"\n ) %>% factor(levels = c(\"low\", \"medium\", \"high\"))\n )\n\nAs in the previous chapter, it’s useful to explore multiple factors when possible. So I’d like us to take the data about political affiliation to visualise alongside our religion and spirituality data. this will help us to see where effects are more or less significant and give us a point of comparison.\n\n## Q53 subsetting based on Political LR orientation --------------------------------------------------------------\n# Generate low/med/high bins based on Mean and SD\nclimate_experience_data <- climate_experience_data %>%\n mutate(\n Q53_bin = case_when(\n Q53_1 > mean(Q53_1) + sd(Q53_1) ~ \"high\",\n Q53_1 < mean(Q53_1) - sd(Q53_1) ~ \"low\",\n TRUE ~ \"medium\"\n ) %>% factor(levels = c(\"low\", \"medium\", \"high\"))\n )\n\nNow let’s use those bins to explore some of the responses about attitudes towards climate change:\n\n# Faceted plot working with 3x3 grid\ndf <- select(climate_experience_data, Q52_bin, Q53_bin, Q57_bin, Q58)\nnames(df) <- c(\"Q52_bin\", \"Q53_bin\", \"Q57_bin\", \"response\")\nfacet_names <- c(`Q52_bin` = \"Spirituality\", `Q53_bin` = \"Politics L/R\", `Q57_bin` = \"Religiosity\", `low`=\"low\", `medium`=\"medium\", `high`=\"high\")\nfacet_labeller <- function(variable,value){return(facet_names[value])}\ndf$response <- factor(df$response, ordered = TRUE, levels = c(\"1\", \"2\", \"3\", \"4\", \"5\"))\ndf$response <- fct_recode(df$response, \"More than once a week\" = \"1\", \"Once a week\" = \"2\", \"At least once a month\" = \"3\", \"Only on special holy days\" = \"4\", \"Never\" = \"5\")\ndf %>% \n # we need to get the data including facet info in long format, so we use pivot_longer()\n pivot_longer(!response, names_to = \"bin_name\", values_to = \"b\") %>% \n # add counts for plot below\n count(response, bin_name, b) %>%\n group_by(bin_name,b) %>%\n mutate(perc=paste0(round(n*100/sum(n),1),\"%\")) %>% \n # run ggplot\n ggplot(aes(x = n, y = \"\", fill = response)) +\n geom_col(position=position_fill(), aes(fill=response)) +\n geom_text(aes(label = perc), position = position_fill(vjust=.5), size=2) +\n scale_fill_brewer(palette = \"Dark2\", type = \"qual\") +\n scale_x_continuous(labels = scales::percent_format()) +\n facet_grid(vars(b), vars(bin_name), labeller=as_labeller(facet_names)) + \n labs(caption = caption, x = \"\", y = \"\") + \n guides(fill = guide_legend(title = NULL))\n\n\n\nggsave(\"figures/q58_faceted.png\", width = 30, height = 10, units = \"cm\")\n\n\n\n\n\n\n\n\n\nWhat is Religion?\n\n\n\nContent tbd\n\n\n\n\n\n\n\n\nHybrid Religious Identity\n\n\n\nContent tbd\n\n\n\n\n\n\n\n\nWhat is Secularisation?\n\n\n\nContent tbd" }, { "objectID": "chapter_2.html#references", diff --git a/hacking_religion/chapter_2.qmd b/hacking_religion/chapter_2.qmd index dc8238d..50c44b5 100644 --- a/hacking_religion/chapter_2.qmd +++ b/hacking_religion/chapter_2.qmd @@ -131,7 +131,6 @@ plot1 <- ggplot(religious_affiliation_ethnicity_sums, aes(x = n, y = Religion)) geom_col(colour = "white") + facet_wrap(~Ethnicity, scales="free_x") ggsave("chart.png", plot=plot1, width = 8, height = 10, units=c("in")) - ``` ## Working With a Continum: Religiosity and Spirituality @@ -161,14 +160,13 @@ caption <- "Respondent Religiosity" ggplot(religiosity_sums, aes(x = response, y = n, color=response)) + geom_col(colour = "white", aes(fill = response)) + # <1> ## get rid of all elements except y axis labels + adjust plot margin - coord_flip() + # <1> + coord_flip() + # <2> theme(plot.margin = margin(rep(15, 4))) + labs(caption = caption) ``` -We've added a few elements here: -1. Colors, because colours are fun. -2. `coord_flip` to rotate the chart so we have bars going horizontally +1. We've added colors, because colours are fun. +2. Also new here is `coord_flip` to rotate the chart so we have bars going horizontally Since we're thinking about how things look just now, let's play with themes for a minute. `ggplot` is a really powerful tool for visualising information, but it also has some quite nice features for making things look pretty. @@ -213,15 +211,33 @@ climate_experience_data$Q52_score <- rowMeans(select(climate_experience_data, Q5 Like we did in chapter 1, let's start by exploring the data and get a bit of a sense of the character of the responses overall. One good place to start is to find out the mean response for our two continum questions: +```{r} +# Spirituality first: +mean(climate_experience_data$Q52_score) + +# Then religiosity +mean(climate_experience_data$Q57_1) +``` + + + ```{r} # t_testing and means # Spirituality scale +library(rstatix) +religiosity_stats <- as.tibble(climate_experience_data$Q57_1) +spirituality_stats <- as.tibble(climate_experience_data$Q52_score) + +plot(religiosity_stats ~ spirituality_stats, data=CO2) + +stats %>% get_summary_stats(value, type="mean_sd") + # JK note to self: need to fix stat_summary plot here - # stat_summary(climate_experience_data$Q52_score) -mean(climate_experience_data$Q52_score) + + # Q57 Regardless of whether you belong to a particular religion, how religious would you say you are? # 0-10, Not religious at all => Very religious; mean=5.58