chapter 1 updates to github web hosting

This commit is contained in:
Jeremy Kidwell 2025-01-09 13:31:56 +00:00
parent 59902f218f
commit 93adab4675
80 changed files with 3008 additions and 197 deletions

View file

@ -2,7 +2,7 @@
<html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en"><head>
<meta charset="utf-8">
<meta name="generator" content="quarto-1.4.549">
<meta name="generator" content="quarto-1.4.551">
<meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=yes">
@ -174,7 +174,7 @@ div.csl-indent {
<li class="sidebar-item">
<div class="sidebar-item-container">
<a href="./chapter_2.html" class="sidebar-item-text sidebar-link">
<span class="menu-text"><span class="chapter-number">2</span>&nbsp; <span class="chapter-title">Getting into the nitty-gritty details</span></span></a>
<span class="menu-text"><span class="chapter-number">2</span>&nbsp; <span class="chapter-title">Different ways to measure religion using data science</span></span></a>
</div>
</li>
<li class="sidebar-item">
@ -253,7 +253,8 @@ div.csl-indent {
</header>
<p>Well get to the good stuff in a moment, but first we need to do a bit of setup. The code provided here is intended to set up your workspace and is also necessary for the <code>quarto</code> application we use to build this book. Quarto is an application which blends together text and blocks of code. You can ignore most of it for now, though if youre running the code as we go along, youll definitely want to include these lines, as they create directories where your files will go as you create charts and extract data below and tells R where to find those files:</p>
<p>In this chapter were going to do some exciting things with census data. This is a very important dataset, often analysed, but much less frequently with regards to the subject of religion and almost never with the level of granularity youll learn to work with over the course of this chapter.</p>
<p>Well get to the good stuff in a moment, but first we need to do a bit of setup. The code provided here is intended to set up your workspace and is also necessary for the <code>quarto</code> application we use to build this book. If you hadnt already noticed, this book is also generated by live (and living!) R code. Quarto is an application which blends together text and blocks of code to produce books. You can ignore most of it for now, though if youre running the code as we go along, youll definitely want to include these lines, as they create directories where your files will go as you create charts and extract data below and tells R where to find those files:</p>
<div class="cell">
<div class="sourceCode cell-code" id="cb1"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb1-1"><a href="#cb1-1" aria-hidden="true" tabindex="-1"></a><span class="fu">setwd</span>(<span class="st">"/Users/kidwellj/gits/hacking_religion_textbook/hacking_religion"</span>)</span>
<span id="cb1-2"><a href="#cb1-2" aria-hidden="true" tabindex="-1"></a><span class="fu">library</span>(here) <span class="sc">|&gt;</span> <span class="fu">suppressPackageStartupMessages</span>()</span>
@ -423,7 +424,7 @@ div.csl-indent {
</table>
</div>
</div>
<p>You can see how Ive nested the previous command inside the <code>kable</code> command. For reference, in some cases when youre working with really complex scripts with many different libraries and functions, they may end up with functions that have the same name. You can specify the library where the function is meant to come from by preceding it with :: as weve done <code>knitr::</code> above. The same kind of output can be gotten using <code>tail</code>:</p>
<p>You can see how Ive nested the previous command inside the <code>kable</code> command. For reference, in some cases when youre working with really complex scripts with many different libraries and functions, they may end up with functions that have the same name, and you may unwittingly run a function from the wrong library. You can specify the library where the function is meant to come from by preceding it with :: as weve done <code>knitr::</code> above. The same kind of output can be gotten using <code>tail</code> which shows the final lines of a given data object:</p>
<div class="cell">
<div class="sourceCode cell-code" id="cb8"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb8-1"><a href="#cb8-1" aria-hidden="true" tabindex="-1"></a>knitr<span class="sc">::</span><span class="fu">kable</span>(<span class="fu">tail</span>(uk_census_2021_religion))</span></code><button title="Copy to Clipboard" class="code-copy-button"><i class="bi"></i></button></pre></div>
<div class="cell-output-display">
@ -550,12 +551,14 @@ div.csl-indent {
</section>
<section id="parsing-and-exploring-your-data" class="level1 page-columns page-full" data-number="5">
<h1 data-number="5"><span class="header-section-number">5</span> Parsing and Exploring your data</h1>
<p>The first thing youre going to want to do is to take a smaller subset of a large data set, either by filtering out certain columns or rows. Now lets say we want to just work with the data from the West Midlands, and wed like to omit some of the columns. We can choose a specific range of columns using <code>select</code>, like this:</p>
<p>You can use the <code>filter</code> command to do this. To give an example, <code>filter</code> can pick a single row in the following way:</p>
<p>The first thing youre going to want to do is to take a smaller subset of a large data set, either by filtering out certain columns or rows. Lets say we want to just work with the data from the West Midlands and wed like to omit some of the other columns which relate to different geographic areas. We can choose a specific range of columns using <code>select</code>, like this:</p>
<p>You can use the <code>filter</code> command to do this. To give an example, <code>filter</code> can pick a single <em>row</em> in the following way:</p>
<div class="cell">
<div class="sourceCode cell-code" id="cb9"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb9-1"><a href="#cb9-1" aria-hidden="true" tabindex="-1"></a>uk_census_2021_religion_wmids <span class="ot">&lt;-</span> uk_census_2021_religion <span class="sc">%&gt;%</span> <span class="fu">filter</span>(geography<span class="sc">==</span><span class="st">"West Midlands"</span>) </span></code><button title="Copy to Clipboard" class="code-copy-button"><i class="bi"></i></button></pre></div>
</div>
<p>Now well use select in a different way to narrow our data to specific columns that are needed (no totals!).</p>
<p>In the line above, youll see that weve created a new object which contains this more specific subset of the original data. You can also overwrite your original object with the new information, and as you go along youll need to make decisions about whether to keep many iterations as different objects, or if you want to try and hold onto only the bare essentials.</p>
<p>Its also worth noting that there are only a few rules for naming objects (you cant have spaces, for one thing), so youll want to come up with a specific convention that works for you. I tend to assign a name for each object that indicates the dataset it has come from and then chain on further names using underscore characters which indicate what kind of subset it is. You may want to be careful about letting your names get too long, and find comprehensible ways to abbreviate.</p>
<p>Now well use select in a different way to narrow our data to specific <em>columns</em> that are needed (no totals!).</p>
<div class="page-columns page-full"><p></p><div class="no-row-height column-margin column-container"><span class="margin-aside">Some readers will want to pause here and check out Hadley Wickhams “R For Data Science” book, in the section, <a href="https://r4ds.hadley.nz/data-visualize#introduction">“Data visualisation”</a> to get a fuller explanation of how to explore your data.</span></div></div>
<p>In keeping with my goal to demonstrate data science through examples, were going to move on to producing some snappy looking charts for this data.</p>
</section>
@ -566,9 +569,10 @@ div.csl-indent {
<div class="sourceCode cell-code" id="cb10"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb10-1"><a href="#cb10-1" aria-hidden="true" tabindex="-1"></a>uk_census_2021_religion_wmids <span class="ot">&lt;-</span> uk_census_2021_religion_wmids <span class="sc">%&gt;%</span> <span class="fu">select</span>(no_religion<span class="sc">:</span>no_response)</span>
<span id="cb10-2"><a href="#cb10-2" aria-hidden="true" tabindex="-1"></a>uk_census_2021_religion_wmids <span class="ot">&lt;-</span> <span class="fu">gather</span>(uk_census_2021_religion_wmids)</span></code><button title="Copy to Clipboard" class="code-copy-button"><i class="bi"></i></button></pre></div>
</div>
<p>There are two basic ways to do visualisations in R. You can work with basic functions in R, often called “base R” or you can work with an alternative library called ggplot:</p>
<p>There are two basic ways to do visualisations in R. You can work with basic functions in R, often called “base R” or you can work with an alternative (and extremely popular) library called ggplot which aims to streamline the coding you need to make a chart:</p>
<section id="base-r" class="level2" data-number="6.1">
<h2 data-number="6.1" class="anchored" data-anchor-id="base-r"><span class="header-section-number">6.1</span> Base R</h2>
<p>Heres the code you can use to create a new data object which contains the information necessary for our chart. Ive just used the generic name “df” because we wont hold on to this chart. Youll also see that Ive organised the data in descending order using the base R function <code>order()</code>. In the next line, we use the Base R function “barplot” to create a chart.</p>
<div class="cell">
<div class="sourceCode cell-code" id="cb11"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb11-1"><a href="#cb11-1" aria-hidden="true" tabindex="-1"></a>df <span class="ot">&lt;-</span> uk_census_2021_religion_wmids[<span class="fu">order</span>(uk_census_2021_religion_wmids<span class="sc">$</span>value,<span class="at">decreasing =</span> <span class="cn">TRUE</span>),]</span>
<span id="cb11-2"><a href="#cb11-2" aria-hidden="true" tabindex="-1"></a><span class="fu">barplot</span>(<span class="at">height=</span>df<span class="sc">$</span>value, <span class="at">names=</span>df<span class="sc">$</span>key)</span></code><button title="Copy to Clipboard" class="code-copy-button"><i class="bi"></i></button></pre></div>
@ -583,13 +587,14 @@ div.csl-indent {
</section>
<section id="ggplot" class="level2 page-columns page-full" data-number="6.2">
<h2 data-number="6.2" class="anchored" data-anchor-id="ggplot"><span class="header-section-number">6.2</span> GGPlot</h2>
<p>The conventions of GGPlot take a bit of getting used to, but its a very powerful tool which will scale to quite complicated charts.</p>
<div class="cell">
<div class="sourceCode cell-code" id="annotated-cell-10"><pre class="sourceCode r code-annotation-code code-with-copy"><code class="sourceCode r"><span id="annotated-cell-10-1"><a href="#annotated-cell-10-1" aria-hidden="true" tabindex="-1"></a><span class="fu">ggplot</span>(uk_census_2021_religion_wmids, <span class="fu">aes</span>(<span class="at">x =</span> key, <span class="at">y =</span> value)) <span class="sc">+</span> <span class="fu">geom_bar</span>(<span class="at">stat =</span> <span class="st">"identity"</span>)</span></code><button title="Copy to Clipboard" class="code-copy-button"><i class="bi"></i></button></pre></div>
<div class="cell-annotation">
<dl class="code-annotation-container-grid">
<dt data-target-cell="annotated-cell-11" data-target-annotation="2">2</dt>
<dd>
<span data-code-cell="annotated-cell-11" data-code-lines="1" data-code-annotation="2">Well re-order the column by size.</span>
<span data-code-cell="annotated-cell-11" data-code-lines="1" data-code-annotation="2">Then we re-order the column by size.</span>
</dd>
</dl>
</div>
@ -609,7 +614,7 @@ div.csl-indent {
</div>
</div>
</div>
<p>Lets assume were working with a data set that doesnt include a “totals” column and that we might want to get sums for each column. This is pretty easy to do in R. As youll see below, we are going to take the original table, and overwrite it with a new column added:</p>
<p>This initial chart doesnt include a “totals” column, as it isnt in the data and these plotting tools simply represent whatever data you put into them. Its nice to have a list of sums for each column, and this is pretty easy to do in R. As youll see below, we are going to take the original table, and overwrite it with a new column added:</p>
<div class="cell">
<div class="sourceCode cell-code" id="annotated-cell-12"><pre class="sourceCode r code-annotation-code code-with-copy code-annotated"><code class="sourceCode r"><a class="code-annotation-anchor" data-target-cell="annotated-cell-12" data-target-annotation="1" onclick="event.preventDefault();">1</a><span id="annotated-cell-12-1" class="code-annotation-target"><a href="#annotated-cell-12-1" aria-hidden="true" tabindex="-1"></a>uk_census_2021_religion_totals <span class="ot">&lt;-</span> uk_census_2021_religion <span class="sc">%&gt;%</span> <span class="fu">select</span>(no_religion<span class="sc">:</span>no_response)</span>
<span id="annotated-cell-12-2"><a href="#annotated-cell-12-2" aria-hidden="true" tabindex="-1"></a>uk_census_2021_religion_totals <span class="ot">&lt;-</span> uk_census_2021_religion_totals <span class="sc">%&gt;%</span></span>
@ -628,7 +633,7 @@ div.csl-indent {
</dd>
<dt data-target-cell="annotated-cell-12" data-target-annotation="3">3</dt>
<dd>
<span data-code-cell="annotated-cell-12" data-code-lines="4" data-code-annotation="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()</span>
<span data-code-cell="annotated-cell-12" data-code-lines="4" data-code-annotation="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 <code>gather()</code></span>
</dd>
<dt data-target-cell="annotated-cell-12" data-target-annotation="4">4</dt>
<dd>
@ -644,11 +649,11 @@ div.csl-indent {
</div>
</div>
</div>
<p>You might have noticed that these two dataframes give us somewhat different results. But with data science, its much more interesting to compare these two side-by-side in a visualisation. We can join these two dataframes and plot the bars side by side using <code>bind()</code> - which can be done by columns with cbind() and rows using rbind():</p>
<p>You might notice that these two dataframes give us somewhat different results. But with data science, its much more interesting to compare these two side-by-side in a visualisation. We can join these two dataframes and plot the bars side by side using <code>bind()</code> - which can be done by columns with <code>cbind()</code> and rows using <code>rbind()</code>:</p>
<div class="cell">
<div class="sourceCode cell-code" id="cb12"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb12-1"><a href="#cb12-1" aria-hidden="true" tabindex="-1"></a>uk_census_2021_religion_merged <span class="ot">&lt;-</span> <span class="fu">rbind</span>(uk_census_2021_religion_totals, uk_census_2021_religion_wmids)</span></code><button title="Copy to Clipboard" class="code-copy-button"><i class="bi"></i></button></pre></div>
</div>
<p>Do you notice theres going to be a problem here? How can we tell one set from the other? We need to add in something idenfiable first! This isnt too hard to do as we can simply create a new column for each with identifiable information before we bind them:</p>
<p>Do you notice theres going to be a problem here? How can we tell one set from the other? We need to add in something idenfiable first! To do this we can simply create a new column for each with identifiable information before we bind them:</p>
<div class="cell">
<div class="sourceCode cell-code" id="cb13"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb13-1"><a href="#cb13-1" aria-hidden="true" tabindex="-1"></a>uk_census_2021_religion_totals<span class="sc">$</span>dataset <span class="ot">&lt;-</span> <span class="fu">c</span>(<span class="st">"totals"</span>)</span>
<span id="cb13-2"><a href="#cb13-2" aria-hidden="true" tabindex="-1"></a>uk_census_2021_religion_wmids<span class="sc">$</span>dataset <span class="ot">&lt;-</span> <span class="fu">c</span>(<span class="st">"wmids"</span>)</span>
@ -684,9 +689,9 @@ div.csl-indent {
</div>
</div>
</div>
<p>Now you can see a very rough comparison, which sets bars from the West Midlands data and UK-wide total data side by side for each category. The same principles that weve used here can be applied to draw in more data. You could, for example, compare census data from different years, e.g.&nbsp;2001 2011 and 2021, as well do below. Our use of <code>dplyr::mutate</code> above can be repeated to add an infinite number of further series which can be plotted in bar groups.</p>
<p>This chart gives us a comparison which sets bars from the West Midlands data and UK-wide total data side by side for each category. The same principles that weve used here can be applied to draw in more data. You could, for example, compare census data from different years, e.g.&nbsp;2001 2011 and 2021, as well do below. Our use of <code>dplyr::mutate</code> above can be repeated to add an infinite number of further series which can be plotted in bar groups.</p>
<p>Well draw this data into comparison with later sets in the next chapter. But the one glaring issue which remains for our chart is that its lacking in really any aesthetic refinements. This is where <code>ggplot</code> really shines as a tool as you can add all sorts of things.</p>
<p>The <code>ggplot</code> tool basically works by stacking on additional elements using <code>+</code>. So, for example, lets say we want to improve the colours used for our bars. You can specify the formatting for the fill on the <code>scale</code> by tacking on <code>scale_fill_brewer</code>. This uses a particular tool (and a personal favourite of mine) called <code>colorbrewer</code>. Part of my appreciation of this tool is that you can pick colours which are not just visually pleasing, and produce useful contrast / complementary schemes, but you can also work proactively to accommodate colourblindness. Working with colour schemes which can be divergent in a visually obvious way will be even more important when we work on geospatial data and maps in a later chapter.</p>
<p>The <code>ggplot</code> tool works by stacking additional elements on to your original plot using <code>+</code>. So, for example, lets say we want to improve the colours used for our bars. You can specify the formatting for the fill on the <code>scale</code> by tacking on <code>scale_fill_brewer</code>. This uses a particular tool (and a personal favourite of mine) called <code>colorbrewer</code>. Part of my appreciation of this tool is that you can pick colours which are not just visually pleasing, and produce useful contrast / complementary schemes, but you can also work proactively to accommodate colourblindness. Working with colour schemes which can be divergent in a visually obvious way will be even more important when we work on geospatial data and maps in a later chapter.</p>
<div class="cell">
<div class="sourceCode cell-code" id="cb15"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb15-1"><a href="#cb15-1" aria-hidden="true" tabindex="-1"></a><span class="fu">ggplot</span>(uk_census_2021_religion_merged, <span class="fu">aes</span>(<span class="at">fill=</span>dataset, <span class="at">x=</span>key, <span class="at">y=</span>perc)) <span class="sc">+</span> <span class="fu">geom_bar</span>(<span class="at">position=</span><span class="st">"dodge"</span>, <span class="at">stat =</span><span class="st">"identity"</span>) <span class="sc">+</span> <span class="fu">scale_fill_brewer</span>(<span class="at">palette =</span> <span class="st">"Set1"</span>)</span></code><button title="Copy to Clipboard" class="code-copy-button"><i class="bi"></i></button></pre></div>
<div class="cell-output-display">
@ -721,22 +726,9 @@ div.csl-indent {
</div>
</div>
</div>
</section>
</section>
<section id="telling-the-truth-in-data-science-is-your-chart-accurate" class="level1" data-number="7">
<h1 data-number="7"><span class="header-section-number">7</span> Telling the truth in data science: Is your chart accurate?</h1>
<p>If youve been following along up until this point, youll now have produced a fairly complete data visualisation for the UK census. There is some technical work yet to be done fine-tuning the visualisation of our chart here, but Id like to pause for a moment and consider an ethical question drawn from the principles I outlined in the introduction: is the title of this chart truthful and accurate?</p>
<p>On one hand, it is a straight-forward reference to the nature of the question asked on the 2021 census survey instrument, e.g.&nbsp;something like “what is your religious affiliation”. However, as you will see in the next chapter, large data sets from the same year which asked a fairly similar question yield different results. Part of this could be attributed to the amount of non-respose to this specific question which, in the 2021 census is between 5-6% across many demographics. Its possible (though perhaps unlikely) that all those non-responses were Sikh respondents who felt uncomfortable identifying themselves on such a survey. If even half of the non-responses were of this nature, this would dramatically shift the results especially in comparison to other minority groups. So there is some work for us to do here in representing non-response as a category on the census.</p>
<p>Its equally possible that someone might feel uncertain when answering, but nonetheless land on a particular decision marking “Christian” when they wondered if they should instead tick “no religion. Some surveys attempt to capture uncertainty in this way, asking respondents to mark how confident they are about their answers, or allowing respondents to choose multiple answers, but the census hasnt captured this so we simply dont know. Its possible that a large portion of respondents in the”Christian” category were hovering between this and another response, and they might shift their answers when responding on a different day or in the context of a particular experience like a good or bad day attending church, or perhaps having just had a conversation with a friend which shifted their thinking.</p>
<p>Even the inertia of survey design can have an effect on this, so responding to other questions in a particular way, thinking about ethnic identity, for example, can prime a person to think about their religious identity in a different or more focussed way, altering their response to the question. If someone were to ask you on a survey “are you hungry” you might say “no,” but if theyd previously asked you a hundred questions about your favourite pizza toppings you might have been primed to think about food and when you arrive at the same question, even at the same time in the day, answer differently. This can be the case for some ethnicity and religion pairings, which well explore a bit more in the next chapter.</p>
<p>Given this challenge, some survey instruments randomise the order of questions. This hasnt been done on the census (which would have been quite hard work given that most of the instruments were printed hard copies!), so again, we cant really be sure if those answers given are stable in such a way.</p>
<p>Finally, researchers have also found that when people are asked to mark their religious affiliation, sometimes they can prefer to mark more than one answer. A person might consider themselves to be “Muslim” but also “Spiritual but not religious” preferring the combination of those identities. It is also the case that respondents can identify with more unexpected hybrid religious identities, such as “Christian” and “Hindu”. One might assume that these are different religions without many doctrinal overlaps, but researchers have found that in actual practice, its perfectly possible for people to inhabit two categories which the researcher might assume are opposed.</p>
<p>The UK census only allows respondents to tick a single box for the religion category. It is worth noting that, in contrast, the responses for ethnicity allow for combinations. Given that this is the case, its impossible to know which way a person went at the fork in the road as they were forced to choose just one half of this kind of hybrid identity. Did they feel a bit more Buddhist that day? Or spiritual?</p>
<p>Finally, it is interesting for us to consider exactly what it means for a person when they tick a box like this. The census doesnt specify how one should calculate the basis of your participation. Is it because they attend synagogue on a weekly basis? Some persons would consider weekly attendance at workship a prerequisite for membership in a group, but others would not. Indeed we can infer from surveys and research which aims to track rates of participation in weekly worship that many people who tick boxes for particular religious identities on the census have never attended a worship service at all.</p>
<p>What does this mean for our results? Are they completely unreliable and invalid? I dont think this is the case or that taking a clear-eyed look at the force and stability of our underlying data should be cause for despair. Instead, the most appropriate response is humility. Someone has made a statement which is recorded in the census, of this we can be sure. They felt it to be an accurate response on some level based on the information they had at the time. And with regard to the census, it is a massive dataset, covering much of the population, and this large sample size does afford some additional validity. The easiest way to represent all this reality in the form of speaking truthfully about our data is to acknowledge that however valid it may seem, it is nonetheless a snapshot. For this reason, I would always advise that the best title for a chart is one which specifies the data set.</p>
<p>So if we are going to fine-tune our visuals to ensure they comport with our hacker principles and speak truthfully, we should also probably do something different with those non-responses:</p>
<p>Its also a bit hard to read our Y-axis labels with everything getting cramped down there, so lets rotate that text to 180 degrees so those labels are clear:</p>
<div class="cell">
<div class="sourceCode cell-code" id="cb18"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb18-1"><a href="#cb18-1" aria-hidden="true" tabindex="-1"></a><span class="fu">ggplot</span>(uk_census_2021_religion_merged, <span class="fu">aes</span>(<span class="at">fill=</span><span class="fu">fct_reorder</span>(dataset, value), <span class="at">x=</span><span class="fu">reorder</span>(key,<span class="sc">-</span>value),value, <span class="at">y=</span>perc)) <span class="sc">+</span> <span class="fu">geom_bar</span>(<span class="at">position=</span><span class="st">"dodge"</span>, <span class="at">stat =</span><span class="st">"identity"</span>, <span class="at">colour =</span> <span class="st">"black"</span>) <span class="sc">+</span> <span class="fu">scale_fill_brewer</span>(<span class="at">palette =</span> <span class="st">"Set1"</span>) <span class="sc">+</span> <span class="fu">ggtitle</span>(<span class="st">"Religious Affiliation in the 2021 Census of England and Wales"</span>) <span class="sc">+</span> <span class="fu">xlab</span>(<span class="st">""</span>) <span class="sc">+</span> <span class="fu">ylab</span>(<span class="st">""</span>)</span></code><button title="Copy to Clipboard" class="code-copy-button"><i class="bi"></i></button></pre></div>
<div class="sourceCode cell-code" id="cb18"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb18-1"><a href="#cb18-1" aria-hidden="true" tabindex="-1"></a><span class="fu">ggplot</span>(uk_census_2021_religion_merged, <span class="fu">aes</span>(<span class="at">fill=</span><span class="fu">fct_reorder</span>(dataset, value), <span class="at">x=</span><span class="fu">reorder</span>(key,<span class="sc">-</span>value),value, <span class="at">y=</span>perc)) <span class="sc">+</span> <span class="fu">geom_bar</span>(<span class="at">position=</span><span class="st">"dodge"</span>, <span class="at">stat =</span><span class="st">"identity"</span>, <span class="at">colour =</span> <span class="st">"black"</span>) <span class="sc">+</span> <span class="fu">scale_fill_brewer</span>(<span class="at">palette =</span> <span class="st">"Set1"</span>) <span class="sc">+</span> <span class="fu">ggtitle</span>(<span class="st">"Religious Affiliation in the UK: 2021"</span>) <span class="sc">+</span> <span class="fu">xlab</span>(<span class="st">""</span>) <span class="sc">+</span> <span class="fu">ylab</span>(<span class="st">""</span>) <span class="sc">+</span> <span class="fu">theme</span>(<span class="at">axis.text.x =</span> <span class="fu">element_text</span>(<span class="at">angle =</span> <span class="dv">90</span>, <span class="at">vjust =</span> <span class="fl">0.5</span>, <span class="at">hjust=</span><span class="dv">1</span>))</span></code><button title="Copy to Clipboard" class="code-copy-button"><i class="bi"></i></button></pre></div>
<div class="cell-output-display">
<div>
<figure class="figure">
@ -746,9 +738,33 @@ div.csl-indent {
</div>
</div>
</section>
<section id="multifactor-visualisation" class="level1 page-columns page-full" data-number="8">
</section>
<section id="telling-the-truth-in-data-science-is-your-chart-accurate" class="level1" data-number="7">
<h1 data-number="7"><span class="header-section-number">7</span> Telling the truth in data science: Is your chart accurate?</h1>
<p>If youve been following along up until this point, youll have produced a fairly complete data visualisation for the UK census. There is some technical work yet to be done fine-tuning the visualisation of our chart here, but Id like to pause for a moment and consider an ethical question drawn from the principles I outlined in the introduction: is the title of this chart truthful and accurate?</p>
<p>On one hand, it is a straight-forward reference to the nature of the question asked on the 2021 census survey instrument, e.g.&nbsp;something like “what is your religious affiliation”. However, as you will see in the next chapter, other large data sets from the same year which involved a similar question yielded different results. Part of this could be attributed to the amount of non-respose to this specific question which, in the 2021 census is between 5-6% across many demographics. Its possible (though perhaps unlikely) that all those non-responses were (to pick one random example) Jedi religion practitioners who felt uncomfortable identifying themselves on such a census survey. If even half of the non-responses were of this nature, this would dramatically shift the results especially in comparison to other minority groups. So there is some work for us to do here in representing non-response as a category on the census.</p>
<p>Its equally possible that someone might feel uncertain when answering, but nonetheless land on a particular decision marking “Christian” when they wondered if they should instead tick “no religion. Some surveys attempt to capture uncertainty in this way, asking respondents to mark how confident they are about their answers, or allowing respondents to choose multiple answers, but the makers of the census made a specific choice not to capture this so we simply dont know. Its possible that a large portion of respondents in the”Christian” category were hovering between this and another response and they might shift their answers when responding on a different day or in the context of a particular experience like a good or bad day attending church, or perhaps having just had a conversation with a friend which shifted their thinking.</p>
<p>Even the inertia of survey design can have an effect on this, so responding to other questions in a particular way, thinking about ethnic identity, for example, can prime a person to think about their religious identity in a different or more focussed way, altering their response to the question. If someone were to ask you on a survey “are you hungry” you might say “no,” but if theyd previously asked you a hundred questions about your favourite pizza toppings you might have been primed to think about food and when you arrive at the same question, even at the same time in the day, your answer would be an enthusiastic “yes”. This can be the case for some ethnicity and religion pairings which may have priming interrelations, which well explore a bit more in the next chapter.</p>
<p>Given this challenge, some survey instruments randomise the order of questions. This hasnt been done on the census (which would have been quite hard work given that most of the instruments were printed hard copies!), so again, we cant really be sure if those answers given are stable in such a way.</p>
<p>Finally, researchers have also found that when people are asked to mark their religious affiliation, sometimes they can prefer to mark more than one answer. A person might consider themselves to be “Muslim” but also “Spiritual but not religious” preferring the combination of those identities. It is also the case that respondents do in practice identify with less expected hybrid religious identities as well, such as “Christian” and “Hindu”. One might assume that these are different religions without many doctrinal overlaps, but researchers have found that in actual practice, its perfectly possible for some people to inhabit two or more categories which the researcher might assume are opposed.</p>
<p>The UK census only allows respondents to tick a single box for the religion category. It is worth noting that, in contrast, the responses for ethnicity allow for combinations. Given that this is the case, its impossible to know which way a person went at the fork in the road as they were forced to choose just one half of this kind of hybrid identity. Did they feel a bit more Buddhist that day? Or spiritual?</p>
<p>Finally, it is interesting for us to consider exactly what it means for a person when they tick a box like this. The census doesnt specify how one should calculate the basis of your participation. Is it because they attend synagogue on a weekly basis? Some persons would consider weekly attendance at workship a prerequisite for membership in a group, but others would not. Indeed we can infer from surveys and research which aims to track rates of participation in weekly worship that many people who tick boxes for particular religious identities on the census have never attended a worship service at all.</p>
<p>What does this mean for our results? Are they completely unreliable and invalid? I dont think this is the case or that taking a clear-eyed look at the force and stability of our underlying data should be cause for despair. Instead, the most appropriate response is humility. Someone has made a statement which is recorded in the census, of this we can be sure. They felt it to be an accurate response on some level based on the information they had at the time. And with regard to the census, it is a massive dataset, covering much of the population, and this large sample size does afford some additional validity. The easiest way to represent all this reality in the form of speaking truthfully about our data is to acknowledge that however valid it may seem, it is nonetheless a snapshot. For this reason, I would always advise that the best title for a chart is one which specifies the data set.</p>
<p>So if we are going to fine-tune our visuals to ensure they comport with our hacker principles and speak truthfully, we should also probably do something different with those non-responses:</p>
<div class="cell">
<div class="sourceCode cell-code" id="cb19"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb19-1"><a href="#cb19-1" aria-hidden="true" tabindex="-1"></a><span class="fu">ggplot</span>(uk_census_2021_religion_merged, <span class="fu">aes</span>(<span class="at">fill=</span><span class="fu">fct_reorder</span>(dataset, value), <span class="at">x=</span><span class="fu">reorder</span>(key,<span class="sc">-</span>value),value, <span class="at">y=</span>perc)) <span class="sc">+</span> <span class="fu">geom_bar</span>(<span class="at">position=</span><span class="st">"dodge"</span>, <span class="at">stat =</span><span class="st">"identity"</span>, <span class="at">colour =</span> <span class="st">"black"</span>) <span class="sc">+</span> <span class="fu">scale_fill_brewer</span>(<span class="at">palette =</span> <span class="st">"Set1"</span>) <span class="sc">+</span> <span class="fu">ggtitle</span>(<span class="st">"Religious Affiliation in the 2021 Census of England and Wales"</span>) <span class="sc">+</span> <span class="fu">xlab</span>(<span class="st">""</span>) <span class="sc">+</span> <span class="fu">ylab</span>(<span class="st">""</span>) <span class="sc">+</span> <span class="fu">theme</span>(<span class="at">axis.text.x =</span> <span class="fu">element_text</span>(<span class="at">angle =</span> <span class="dv">90</span>, <span class="at">vjust =</span> <span class="fl">0.5</span>, <span class="at">hjust=</span><span class="dv">1</span>))</span></code><button title="Copy to Clipboard" class="code-copy-button"><i class="bi"></i></button></pre></div>
<div class="cell-output-display">
<div>
<figure class="figure">
<p><img src="chapter_1_files/figure-html/unnamed-chunk-18-1.png" class="img-fluid figure-img" width="672"></p>
</figure>
</div>
</div>
</div>
</section>
<section id="multifactor-visualisation" class="level1" data-number="8">
<h1 data-number="8"><span class="header-section-number">8</span> Multifactor Visualisation</h1>
<p>One element of R data analysis of census datasets that can get really interesting is working with multiple variables. Above weve looked at the breakdown of religious affiliation across the whole of England and Wales (Scotland operates an independent census), and by placing this data alongside a specific region, weve already made a basic entry into working with multiple variables but this can get much more interesting. Adding an additional quantitative variable (also known as bivariate data when you have <em>two</em> variables) into the mix, however can also generate a lot more information and we have to think about visualising it in different ways which can still communicate with visual clarity in spite of the additional visual noise which is inevitable with enhanced complexity. Lets have a look at the way that religion in England and Wales breaks down by ethnicity.</p>
<p>One element of R data analysis of census datasets that can get really interesting is working with multiple variables. Above weve looked at the breakdown of religious affiliation across the whole of England and Wales (Scotland operates an independent census so we havent included it here) and by placing this data alongside a specific region, weve already made a basic entry into working with multiple variables but this can get much more interesting. Adding an additional quantitative variable (also known as bivariate data when you have <em>two</em> variables) into the mix, however can also generate a lot more information and we have to think about visualising it in different ways which can still communicate with visual clarity in spite of the additional visual noise which is inevitable with enhanced complexity. Lets have a look at the way that religion in England and Wales breaks down by ethnicity.</p>
<div class="callout callout-style-default callout-tip callout-titled">
<div class="callout-header d-flex align-content-center" data-bs-toggle="collapse" data-bs-target=".callout-1-contents" aria-controls="callout-1" aria-expanded="false" aria-label="Toggle callout">
<div class="callout-icon-container">
@ -761,49 +777,57 @@ What is Nomis?
</div>
<div id="callout-1" class="callout-1-contents callout-collapse collapse">
<div class="callout-body-container callout-body">
<p>For the UK, census data is made available for programmatic research like this via an organisation called NOMIS. Luckily for us, there is an R library you can use to access nomis directly which greatly simplifies the process of pulling data down from the platform. Its worth noting that if youre not in the UK, there are similar options for other countries. Nearly every R textbook Ive ever seen works with USA census data, so youll find plenty of documentation available on the tools you can use for US Census data. Similarly for the EU, Canada, Austrailia etc.</p>
<p>For the UK, census data is made available for programmatic research like this via an organisation called NOMIS. Luckily for us, there is an R library you can use to access nomis directly which greatly simplifies the process of pulling data down from the platform. Its worth noting that if youre not in the UK, there are similar options for other countries. Nearly every R textbook Ive ever seen works with USA census data (which is part of the reason Ive taken the opportunity to work with a different national census dataset here in this book), so youll find plenty of documentation available on the tools you can use for US Census data. Similarly for the EU, Canada, Austrailia etc.</p>
<p>If you want to draw some data from the nomis platform yourself in R, have a look at the nomis script in our <a href="https://github.com/kidwellj/hacking_religion_cookbook/blob/main/nomis.R">companion cookbook repository</a>. For now, well provide some data extracts for you to use.</p>
</div>
</div>
</div>
<p>Lets start by loading in some of the enhanced tables from nomis with the 2021 religion / ethnicity tables:</p>
<div class="cell">
<div class="sourceCode cell-code" id="cb19"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb19-1"><a href="#cb19-1" aria-hidden="true" tabindex="-1"></a>nomis_extract_census2021 <span class="ot">&lt;-</span> <span class="fu">readRDS</span>(<span class="at">file =</span> (<span class="fu">here</span>(<span class="st">"example_data"</span>, <span class="st">"nomis_extract_census2021.rds"</span>)))</span></code><button title="Copy to Clipboard" class="code-copy-button"><i class="bi"></i></button></pre></div>
<div class="sourceCode cell-code" id="cb20"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb20-1"><a href="#cb20-1" aria-hidden="true" tabindex="-1"></a>nomis_extract_census2021 <span class="ot">&lt;-</span> <span class="fu">readRDS</span>(<span class="at">file =</span> (<span class="fu">here</span>(<span class="st">"example_data"</span>, <span class="st">"nomis_extract_census2021.rds"</span>)))</span></code><button title="Copy to Clipboard" class="code-copy-button"><i class="bi"></i></button></pre></div>
</div>
<p>Im hoping that readers of this book will feel free to pause along the way and “hack” the code to explore questions of their own, perhaps in this case probing the NOMIS data for answers to their own questions. If I tidy things up too much, however, youre likely to be surprised when you get to the real life data sets. So that you can use the code in this book in a reproducible way, Ive started this exercise with what is a more or less raw dump from NOMIS. This means that the data is a bit messy and needs to be filtered down quite a bit so that it only includes the basic stuff that wed like to examine for this particular question. The upside of this is that you can modify this code to draw in different columns etc.</p>
<div class="cell page-columns page-full">
<div class="sourceCode cell-code" id="annotated-cell-22"><pre class="sourceCode r code-annotation-code code-with-copy code-annotated"><code class="sourceCode r"><a class="code-annotation-anchor" data-target-cell="annotated-cell-22" data-target-annotation="1" onclick="event.preventDefault();">1</a><span id="annotated-cell-22-1" class="code-annotation-target"><a href="#annotated-cell-22-1" aria-hidden="true" tabindex="-1"></a>uk_census_2021_religion_ethnicity <span class="ot">&lt;-</span> <span class="fu">select</span>(nomis_extract_census2021, GEOGRAPHY_NAME, C2021_RELIGION_10_NAME, C2021_ETH_8_NAME, OBS_VALUE)</span>
<a class="code-annotation-anchor" data-target-cell="annotated-cell-22" data-target-annotation="2" onclick="event.preventDefault();">2</a><span id="annotated-cell-22-2" class="code-annotation-target"><a href="#annotated-cell-22-2" aria-hidden="true" tabindex="-1"></a>uk_census_2021_religion_ethnicity <span class="ot">&lt;-</span> <span class="fu">filter</span>(uk_census_2021_religion_ethnicity, GEOGRAPHY_NAME<span class="sc">==</span><span class="st">"England and Wales"</span> <span class="sc">&amp;</span> C2021_RELIGION_10_NAME <span class="sc">!=</span> <span class="st">"Total"</span> <span class="sc">&amp;</span> C2021_ETH_8_NAME <span class="sc">!=</span> <span class="st">"Total"</span>)</span>
<a class="code-annotation-anchor" data-target-cell="annotated-cell-22" data-target-annotation="3" onclick="event.preventDefault();">3</a><span id="annotated-cell-22-3" class="code-annotation-target"><a href="#annotated-cell-22-3" aria-hidden="true" tabindex="-1"></a>uk_census_2021_religion_ethnicity <span class="ot">&lt;-</span> <span class="fu">filter</span>(uk_census_2021_religion_ethnicity, C2021_ETH_8_NAME <span class="sc">!=</span> <span class="st">"White: English, Welsh, Scottish, Northern Irish or British"</span> <span class="sc">&amp;</span> C2021_ETH_8_NAME <span class="sc">!=</span> <span class="st">"White: Irish"</span> <span class="sc">&amp;</span> C2021_ETH_8_NAME <span class="sc">!=</span> <span class="st">"White: Gypsy or Irish Traveller, Roma or Other White"</span>)</span>
<a class="code-annotation-anchor" data-target-cell="annotated-cell-22" data-target-annotation="4" onclick="event.preventDefault();">4</a><span id="annotated-cell-22-4" class="code-annotation-target"><a href="#annotated-cell-22-4" aria-hidden="true" tabindex="-1"></a><span class="fu">ggplot</span>(uk_census_2021_religion_ethnicity, <span class="fu">aes</span>(<span class="at">fill=</span>C2021_ETH_8_NAME, <span class="at">x=</span>C2021_RELIGION_10_NAME, <span class="at">y=</span>OBS_VALUE)) <span class="sc">+</span> <span class="fu">geom_bar</span>(<span class="at">position=</span><span class="st">"dodge"</span>, <span class="at">stat =</span><span class="st">"identity"</span>, <span class="at">colour =</span> <span class="st">"black"</span>) <span class="sc">+</span> <span class="fu">scale_fill_brewer</span>(<span class="at">palette =</span> <span class="st">"Set1"</span>) <span class="sc">+</span> <span class="fu">ggtitle</span>(<span class="st">"Religious Affiliation in the 2021 Census of England and Wales"</span>) <span class="sc">+</span> <span class="fu">xlab</span>(<span class="st">""</span>) <span class="sc">+</span> <span class="fu">ylab</span>(<span class="st">""</span>) <span class="sc">+</span> <span class="fu">theme</span>(<span class="at">axis.text.x =</span> <span class="fu">element_text</span>(<span class="at">angle =</span> <span class="dv">90</span>, <span class="at">vjust =</span> <span class="fl">0.5</span>, <span class="at">hjust=</span><span class="dv">1</span>))</span><div class="code-annotation-gutter-bg"></div><div class="code-annotation-gutter"></div></code><button title="Copy to Clipboard" class="code-copy-button"><i class="bi"></i></button></pre></div>
<div class="cell">
<div class="sourceCode cell-code" id="annotated-cell-23"><pre class="sourceCode r code-annotation-code code-with-copy code-annotated"><code class="sourceCode r"><a class="code-annotation-anchor" data-target-cell="annotated-cell-23" data-target-annotation="1" onclick="event.preventDefault();">1</a><span id="annotated-cell-23-1" class="code-annotation-target"><a href="#annotated-cell-23-1" aria-hidden="true" tabindex="-1"></a>uk_census_2021_religion_ethnicity <span class="ot">&lt;-</span> <span class="fu">select</span>(nomis_extract_census2021, GEOGRAPHY_NAME, C2021_RELIGION_10_NAME, C2021_ETH_8_NAME, OBS_VALUE)</span>
<span id="annotated-cell-23-2"><a href="#annotated-cell-23-2" aria-hidden="true" tabindex="-1"></a></span>
<a class="code-annotation-anchor" data-target-cell="annotated-cell-23" data-target-annotation="2" onclick="event.preventDefault();">2</a><span id="annotated-cell-23-3" class="code-annotation-target"><a href="#annotated-cell-23-3" aria-hidden="true" tabindex="-1"></a>uk_census_2021_religion_ethnicity <span class="ot">&lt;-</span> <span class="fu">filter</span>(uk_census_2021_religion_ethnicity, GEOGRAPHY_NAME<span class="sc">==</span><span class="st">"England and Wales"</span> <span class="sc">&amp;</span> C2021_RELIGION_10_NAME <span class="sc">!=</span> <span class="st">"Total"</span> <span class="sc">&amp;</span> C2021_ETH_8_NAME <span class="sc">!=</span> <span class="st">"Total"</span>)</span>
<span id="annotated-cell-23-4"><a href="#annotated-cell-23-4" aria-hidden="true" tabindex="-1"></a></span>
<a class="code-annotation-anchor" data-target-cell="annotated-cell-23" data-target-annotation="3" onclick="event.preventDefault();">3</a><span id="annotated-cell-23-5" class="code-annotation-target"><a href="#annotated-cell-23-5" aria-hidden="true" tabindex="-1"></a>uk_census_2021_religion_ethnicity <span class="ot">&lt;-</span> <span class="fu">filter</span>(uk_census_2021_religion_ethnicity, C2021_ETH_8_NAME <span class="sc">!=</span> <span class="st">"White: English, Welsh, Scottish, Northern Irish or British"</span> <span class="sc">&amp;</span> C2021_ETH_8_NAME <span class="sc">!=</span> <span class="st">"White: Irish"</span> <span class="sc">&amp;</span> C2021_ETH_8_NAME <span class="sc">!=</span> <span class="st">"White: Gypsy or Irish Traveller, Roma or Other White"</span>)</span>
<span id="annotated-cell-23-6"><a href="#annotated-cell-23-6" aria-hidden="true" tabindex="-1"></a></span>
<span id="annotated-cell-23-7"><a href="#annotated-cell-23-7" aria-hidden="true" tabindex="-1"></a><span class="fu">ggplot</span>(uk_census_2021_religion_ethnicity, <span class="fu">aes</span>(<span class="at">fill=</span>C2021_ETH_8_NAME, <span class="at">x=</span>C2021_RELIGION_10_NAME, <span class="at">y=</span>OBS_VALUE)) <span class="sc">+</span></span>
<span id="annotated-cell-23-8"><a href="#annotated-cell-23-8" aria-hidden="true" tabindex="-1"></a> <span class="fu">geom_bar</span>(<span class="at">position=</span><span class="st">"dodge"</span>, <span class="at">stat =</span><span class="st">"identity"</span>, <span class="at">colour =</span> <span class="st">"black"</span>) <span class="sc">+</span> </span>
<span id="annotated-cell-23-9"><a href="#annotated-cell-23-9" aria-hidden="true" tabindex="-1"></a> <span class="fu">scale_fill_brewer</span>(<span class="at">palette =</span> <span class="st">"Set1"</span>) <span class="sc">+</span> </span>
<span id="annotated-cell-23-10"><a href="#annotated-cell-23-10" aria-hidden="true" tabindex="-1"></a> <span class="fu">ggtitle</span>(<span class="st">"Religious Affiliation in the 2021 Census of England and Wales"</span>) <span class="sc">+</span> </span>
<span id="annotated-cell-23-11"><a href="#annotated-cell-23-11" aria-hidden="true" tabindex="-1"></a> <span class="fu">xlab</span>(<span class="st">""</span>) <span class="sc">+</span> <span class="fu">ylab</span>(<span class="st">""</span>) <span class="sc">+</span> </span>
<a class="code-annotation-anchor" data-target-cell="annotated-cell-23" data-target-annotation="4" onclick="event.preventDefault();">4</a><span id="annotated-cell-23-12" class="code-annotation-target"><a href="#annotated-cell-23-12" aria-hidden="true" tabindex="-1"></a> <span class="fu">theme</span>(<span class="at">axis.text.x =</span> <span class="fu">element_text</span>(<span class="at">angle =</span> <span class="dv">90</span>, <span class="at">vjust =</span> <span class="fl">0.5</span>, <span class="at">hjust=</span><span class="dv">1</span>))</span><div class="code-annotation-gutter-bg"></div><div class="code-annotation-gutter"></div></code><button title="Copy to Clipboard" class="code-copy-button"><i class="bi"></i></button></pre></div>
<div class="cell-annotation">
<dl class="code-annotation-container-grid">
<dt data-target-cell="annotated-cell-22" data-target-annotation="1">1</dt>
<dt data-target-cell="annotated-cell-23" data-target-annotation="1">1</dt>
<dd>
<span data-code-cell="annotated-cell-22" data-code-lines="1" data-code-annotation="1">Select relevant columns</span>
<span data-code-cell="annotated-cell-23" data-code-lines="1" data-code-annotation="1">Select relevant columns</span>
</dd>
<dt data-target-cell="annotated-cell-22" data-target-annotation="2">2</dt>
<dt data-target-cell="annotated-cell-23" data-target-annotation="2">2</dt>
<dd>
<span data-code-cell="annotated-cell-22" data-code-lines="2" data-code-annotation="2">Filter down to simplified dataset with England / Wales and percentages without totals</span>
<span data-code-cell="annotated-cell-23" data-code-lines="3" data-code-annotation="2">Filter down to simplified dataset with England / Wales and percentages without totals</span>
</dd>
<dt data-target-cell="annotated-cell-22" data-target-annotation="3">3</dt>
<dt data-target-cell="annotated-cell-23" data-target-annotation="3">3</dt>
<dd>
<span data-code-cell="annotated-cell-22" data-code-lines="3" data-code-annotation="3">The 2021 census data includes white sub-groups so we need to omit those</span>
<span data-code-cell="annotated-cell-23" data-code-lines="5" data-code-annotation="3">The 2021 census data includes white sub-groups so we need to omit those</span>
</dd>
<dt data-target-cell="annotated-cell-22" data-target-annotation="4">4</dt>
<dt data-target-cell="annotated-cell-23" data-target-annotation="4">4</dt>
<dd>
<span data-code-cell="annotated-cell-22" data-code-lines="4" data-code-annotation="4">Lets plot it out and see how things look!</span>
<span data-code-cell="annotated-cell-23" data-code-lines="12" data-code-annotation="4">Lets plot it out and see how things look!</span>
</dd>
</dl>
</div>
<div class="no-row-height column-margin column-container"><div class="cell-output-display">
<div class="cell-output-display">
<div>
<figure class="figure">
<p><img src="chapter_1_files/figure-html/unnamed-chunk-19-1.png" class="img-fluid figure-img" width="672"></p>
<p><img src="chapter_1_files/figure-html/unnamed-chunk-20-1.png" class="img-fluid figure-img" width="672"></p>
</figure>
</div>
</div></div></div>
</div>
</div>
<p>The trouble with using grouped bars here, as you can see, is that there are quite sharp disparities which make it hard to compare in meaningful ways. We could use <a href="https://en.wikipedia.org/wiki/Logarithm#Probability_theory_and_statistics">logarithmic</a> rather than linear scaling as an option, but this is hard for many general public audiences to appreciate without guidance. One alternative quick fix is to extract data from “white” respondents which can then be placed in a separate chart with a different scale.</p>
<div class="callout callout-style-default callout-note callout-titled">
<div class="callout-header d-flex align-content-center" data-bs-toggle="collapse" data-bs-target=".callout-2-contents" aria-controls="callout-2" aria-expanded="false" aria-label="Toggle callout">
@ -817,41 +841,32 @@ Statistics 101: Logarithmic Visualisation
</div>
<div id="callout-2" class="callout-2-contents callout-collapse collapse">
<div class="callout-body-container callout-body">
<p>Content TBD.</p>
<p>Usually, when we display data we think of numbers in a linear way, that is, each centimetre of the x-axis on our chart represents the same quantity as the cm above and below it. This is generally a preferred way to display data, and as close to a “common sense” way of showing things as we might get. However, this kind of linear visualisation works best only in cases where the difference between one category on our chart and the next is relatively uniform. This is, for the most part, the case with our charts above. However, weve hit another scenario here, the difference between the “White” subcategory and all the others is large enough that those other four categories arent really easily perceived on our chart. One way to address this is to leave behind a linear approach to displaying that x-axis data. What if, for example, each step up on our chart didnt represent the same amount of value, e.g.&nbsp;10, 20, 30, 40, 50 etc. but instead represented an increase which followed orders of magnitude, so something more like 10, 100, 1000, 10000, etc. Thats the essence of a logarithmic visualisation, which can much more easily display data that has a very large range or with disparities from one category to another.</p>
</div>
</div>
</div>
<div class="cell page-columns page-full">
<div class="sourceCode cell-code" id="annotated-cell-23"><pre class="sourceCode r code-annotation-code code-with-copy code-annotated"><code class="sourceCode r"><a class="code-annotation-anchor" data-target-cell="annotated-cell-23" data-target-annotation="1" onclick="event.preventDefault();">1</a><span id="annotated-cell-23-1" class="code-annotation-target"><a href="#annotated-cell-23-1" aria-hidden="true" tabindex="-1"></a>uk_census_2021_religion_ethnicity_white <span class="ot">&lt;-</span> <span class="fu">filter</span>(uk_census_2021_religion_ethnicity, C2021_ETH_8_NAME <span class="sc">==</span> <span class="st">"White"</span>)</span>
<a class="code-annotation-anchor" data-target-cell="annotated-cell-23" data-target-annotation="2" onclick="event.preventDefault();">2</a><span id="annotated-cell-23-2" class="code-annotation-target"><a href="#annotated-cell-23-2" aria-hidden="true" tabindex="-1"></a>uk_census_2021_religion_ethnicity_nonwhite <span class="ot">&lt;-</span> <span class="fu">filter</span>(uk_census_2021_religion_ethnicity, C2021_ETH_8_NAME <span class="sc">!=</span> <span class="st">"White"</span>)</span>
<a class="code-annotation-anchor" data-target-cell="annotated-cell-23" data-target-annotation="3" onclick="event.preventDefault();">3</a><span id="annotated-cell-23-3" class="code-annotation-target"><a href="#annotated-cell-23-3" aria-hidden="true" tabindex="-1"></a><span class="fu">ggplot</span>(uk_census_2021_religion_ethnicity_nonwhite, <span class="fu">aes</span>(<span class="at">fill=</span>C2021_ETH_8_NAME, <span class="at">x=</span>C2021_RELIGION_10_NAME, <span class="at">y=</span>OBS_VALUE)) <span class="sc">+</span> <span class="fu">geom_bar</span>(<span class="at">position=</span><span class="st">"dodge"</span>, <span class="at">stat =</span><span class="st">"identity"</span>, <span class="at">colour =</span> <span class="st">"black"</span>) <span class="sc">+</span> <span class="fu">scale_fill_brewer</span>(<span class="at">palette =</span> <span class="st">"Set1"</span>) <span class="sc">+</span> <span class="fu">ggtitle</span>(<span class="st">"Religious Affiliation in the 2021 Census of England and Wales"</span>) <span class="sc">+</span> <span class="fu">xlab</span>(<span class="st">""</span>) <span class="sc">+</span> <span class="fu">ylab</span>(<span class="st">""</span>) <span class="sc">+</span> <span class="fu">theme</span>(<span class="at">axis.text.x =</span> <span class="fu">element_text</span>(<span class="at">angle =</span> <span class="dv">90</span>, <span class="at">vjust =</span> <span class="fl">0.5</span>, <span class="at">hjust=</span><span class="dv">1</span>))</span><div class="code-annotation-gutter-bg"></div><div class="code-annotation-gutter"></div></code><button title="Copy to Clipboard" class="code-copy-button"><i class="bi"></i></button></pre></div>
<div class="cell">
<div class="sourceCode cell-code" id="annotated-cell-24"><pre class="sourceCode r code-annotation-code code-with-copy code-annotated"><code class="sourceCode r"><a class="code-annotation-anchor" data-target-cell="annotated-cell-24" data-target-annotation="1" onclick="event.preventDefault();">1</a><span id="annotated-cell-24-1" class="code-annotation-target"><a href="#annotated-cell-24-1" aria-hidden="true" tabindex="-1"></a>uk_census_2021_religion_ethnicity_white <span class="ot">&lt;-</span> <span class="fu">filter</span>(uk_census_2021_religion_ethnicity, C2021_ETH_8_NAME <span class="sc">==</span> <span class="st">"White"</span>)</span>
<span id="annotated-cell-24-2"><a href="#annotated-cell-24-2" aria-hidden="true" tabindex="-1"></a></span>
<a class="code-annotation-anchor" data-target-cell="annotated-cell-24" data-target-annotation="2" onclick="event.preventDefault();">2</a><span id="annotated-cell-24-3" class="code-annotation-target"><a href="#annotated-cell-24-3" aria-hidden="true" tabindex="-1"></a>uk_census_2021_religion_ethnicity_nonwhite <span class="ot">&lt;-</span> <span class="fu">filter</span>(uk_census_2021_religion_ethnicity, C2021_ETH_8_NAME <span class="sc">!=</span> <span class="st">"White"</span>)</span>
<span id="annotated-cell-24-4"><a href="#annotated-cell-24-4" aria-hidden="true" tabindex="-1"></a></span>
<a class="code-annotation-anchor" data-target-cell="annotated-cell-24" data-target-annotation="3" onclick="event.preventDefault();">3</a><span id="annotated-cell-24-5" class="code-annotation-target"><a href="#annotated-cell-24-5" aria-hidden="true" tabindex="-1"></a><span class="fu">ggplot</span>(uk_census_2021_religion_ethnicity_nonwhite, <span class="fu">aes</span>(<span class="at">fill=</span>C2021_ETH_8_NAME, <span class="at">x=</span>C2021_RELIGION_10_NAME, <span class="at">y=</span>OBS_VALUE)) <span class="sc">+</span> <span class="fu">geom_bar</span>(<span class="at">position=</span><span class="st">"dodge"</span>, <span class="at">stat =</span><span class="st">"identity"</span>, <span class="at">colour =</span> <span class="st">"black"</span>) <span class="sc">+</span> <span class="fu">scale_fill_brewer</span>(<span class="at">palette =</span> <span class="st">"Set1"</span>) <span class="sc">+</span> <span class="fu">ggtitle</span>(<span class="st">"Religious Affiliation in the 2021 Census of England and Wales"</span>) <span class="sc">+</span> <span class="fu">xlab</span>(<span class="st">""</span>) <span class="sc">+</span> <span class="fu">ylab</span>(<span class="st">""</span>) <span class="sc">+</span> <span class="fu">theme</span>(<span class="at">axis.text.x =</span> <span class="fu">element_text</span>(<span class="at">angle =</span> <span class="dv">90</span>, <span class="at">vjust =</span> <span class="fl">0.5</span>, <span class="at">hjust=</span><span class="dv">1</span>))</span><div class="code-annotation-gutter-bg"></div><div class="code-annotation-gutter"></div></code><button title="Copy to Clipboard" class="code-copy-button"><i class="bi"></i></button></pre></div>
<div class="cell-annotation">
<dl class="code-annotation-container-grid">
<dt data-target-cell="annotated-cell-23" data-target-annotation="1">1</dt>
<dt data-target-cell="annotated-cell-24" data-target-annotation="1">1</dt>
<dd>
<span data-code-cell="annotated-cell-23" data-code-lines="1" data-code-annotation="1">Filter down to simplified dataset with England / Wales and percentages without totals</span>
<span data-code-cell="annotated-cell-24" data-code-lines="1" data-code-annotation="1">Filter down to simplified dataset with England / Wales and percentages without totals</span>
</dd>
<dt data-target-cell="annotated-cell-23" data-target-annotation="2">2</dt>
<dt data-target-cell="annotated-cell-24" data-target-annotation="2">2</dt>
<dd>
<span data-code-cell="annotated-cell-23" data-code-lines="2" data-code-annotation="2">Filtering with <code>!=</code> allows us to create a subset where that response is excluded</span>
<span data-code-cell="annotated-cell-24" data-code-lines="3" data-code-annotation="2">Filtering with <code>!=</code> allows us to create a subset where that response is excluded</span>
</dd>
<dt data-target-cell="annotated-cell-23" data-target-annotation="3">3</dt>
<dt data-target-cell="annotated-cell-24" data-target-annotation="3">3</dt>
<dd>
<span data-code-cell="annotated-cell-23" data-code-lines="3" data-code-annotation="3">Lets plot it out and see where weve gotten to!</span>
<span data-code-cell="annotated-cell-24" data-code-lines="5" data-code-annotation="3">Lets plot it out and see where weve gotten to!</span>
</dd>
</dl>
</div>
<div class="no-row-height column-margin column-container"><div class="cell-output-display">
<div>
<figure class="figure">
<p><img src="chapter_1_files/figure-html/unnamed-chunk-20-1.png" class="img-fluid figure-img" width="672"></p>
</figure>
</div>
</div></div></div>
<p>As youll notice, this is a bit better, but this still doesnt quite render with as much visual clarity and communication as Id like. For a better look, we can use a technique in R called “faceting” to create a series of small charts which can be viewed alongside one another. This is just intended to whet you appetite for facetted plots, so I wont break down all the separate elements in great detail as there are other guides which will walk you through the full details of how to use this technique if you want to do a deep dive. For now, youll want to observe that weve augmented the <code>ggplot</code> with a new element called <code>facet_wrap</code> which takes the ethnicity data column as the basis for rendering separate charts.</p>
<div class="cell">
<div class="sourceCode cell-code" id="cb20"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb20-1"><a href="#cb20-1" aria-hidden="true" tabindex="-1"></a><span class="fu">ggplot</span>(uk_census_2021_religion_ethnicity_nonwhite, <span class="fu">aes</span>(<span class="at">x=</span>C2021_RELIGION_10_NAME, <span class="at">y=</span>OBS_VALUE)) <span class="sc">+</span> <span class="fu">geom_bar</span>(<span class="at">position=</span><span class="st">"dodge"</span>, <span class="at">stat =</span><span class="st">"identity"</span>, <span class="at">colour =</span> <span class="st">"black"</span>) <span class="sc">+</span> <span class="fu">facet_wrap</span>(<span class="sc">~</span>C2021_ETH_8_NAME, <span class="at">ncol =</span> <span class="dv">2</span>) <span class="sc">+</span> <span class="fu">scale_fill_brewer</span>(<span class="at">palette =</span> <span class="st">"Set1"</span>) <span class="sc">+</span> <span class="fu">ggtitle</span>(<span class="st">"Religious Affiliation in the 2021 Census of England and Wales"</span>) <span class="sc">+</span> <span class="fu">xlab</span>(<span class="st">""</span>) <span class="sc">+</span> <span class="fu">ylab</span>(<span class="st">""</span>) <span class="sc">+</span> <span class="fu">theme</span>(<span class="at">axis.text.x =</span> <span class="fu">element_text</span>(<span class="at">angle =</span> <span class="dv">90</span>, <span class="at">vjust =</span> <span class="fl">0.5</span>, <span class="at">hjust=</span><span class="dv">1</span>))</span></code><button title="Copy to Clipboard" class="code-copy-button"><i class="bi"></i></button></pre></div>
<div class="cell-output-display">
<div>
<figure class="figure">
@ -860,139 +875,153 @@ Statistics 101: Logarithmic Visualisation
</div>
</div>
</div>
<p>As youll notice, this is a bit better, but this still doesnt quite render with as much visual clarity and communication as Id like. Another approach we can take is to represent each bar as a percentage of the total for that ethnicity subgroup rather than as raw values. We can do this by adding an extra step to our visualisation drawing on the mutate() function which enables us to create a series of groups based on a specific column (e.g.&nbsp;C2021_ETH_8_NAME) and then create an additional column in our dataframe which represents values within each of our groups as percentages of the total rather than raw values:</p>
<div class="cell">
<div class="sourceCode cell-code" id="cb21"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb21-1"><a href="#cb21-1" aria-hidden="true" tabindex="-1"></a>uk_census_2021_religion_ethnicity_percents <span class="ot">&lt;-</span> uk_census_2021_religion_ethnicity <span class="sc">%&gt;%</span></span>
<span id="cb21-2"><a href="#cb21-2" aria-hidden="true" tabindex="-1"></a> <span class="fu">group_by</span>(C2021_ETH_8_NAME) <span class="sc">%&gt;%</span></span>
<span id="cb21-3"><a href="#cb21-3" aria-hidden="true" tabindex="-1"></a> <span class="fu">mutate</span>(<span class="at">Percentage =</span> OBS_VALUE <span class="sc">/</span> <span class="fu">sum</span>(OBS_VALUE) <span class="sc">*</span> <span class="dv">100</span>)</span>
<span id="cb21-4"><a href="#cb21-4" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb21-5"><a href="#cb21-5" aria-hidden="true" tabindex="-1"></a><span class="fu">ggplot</span>(uk_census_2021_religion_ethnicity_percents, <span class="fu">aes</span>(<span class="at">fill=</span>C2021_ETH_8_NAME, <span class="at">x=</span>C2021_RELIGION_10_NAME, <span class="at">y=</span>Percentage)) <span class="sc">+</span></span>
<span id="cb21-6"><a href="#cb21-6" aria-hidden="true" tabindex="-1"></a> <span class="fu">geom_bar</span>(<span class="at">position=</span><span class="st">"dodge"</span>, <span class="at">stat =</span><span class="st">"identity"</span>, <span class="at">colour =</span> <span class="st">"black"</span>) <span class="sc">+</span> </span>
<span id="cb21-7"><a href="#cb21-7" aria-hidden="true" tabindex="-1"></a> <span class="fu">scale_fill_brewer</span>(<span class="at">palette =</span> <span class="st">"Set1"</span>) <span class="sc">+</span> </span>
<span id="cb21-8"><a href="#cb21-8" aria-hidden="true" tabindex="-1"></a> <span class="fu">ggtitle</span>(<span class="st">"Religious Affiliation in the 2021 Census of England and Wales"</span>) <span class="sc">+</span> </span>
<span id="cb21-9"><a href="#cb21-9" aria-hidden="true" tabindex="-1"></a> <span class="fu">xlab</span>(<span class="st">""</span>) <span class="sc">+</span> <span class="fu">ylab</span>(<span class="st">""</span>) <span class="sc">+</span> </span>
<span id="cb21-10"><a href="#cb21-10" aria-hidden="true" tabindex="-1"></a> <span class="fu">theme</span>(<span class="at">axis.text.x =</span> <span class="fu">element_text</span>(<span class="at">angle =</span> <span class="dv">90</span>, <span class="at">vjust =</span> <span class="fl">0.5</span>, <span class="at">hjust=</span><span class="dv">1</span>))</span></code><button title="Copy to Clipboard" class="code-copy-button"><i class="bi"></i></button></pre></div>
<div class="cell-output-display">
<div>
<figure class="figure">
<p><img src="chapter_1_files/figure-html/unnamed-chunk-22-1.png" class="img-fluid figure-img" width="672"></p>
</figure>
</div>
</div>
</div>
<p>As you can see, this gives us a really different sense of representation within each group. Another option we can use here is a technique in R called “faceting” which creates a series of small charts which can be viewed alongside one another. This is just intended to whet you appetite for facetted plots, so I wont break down all the separate elements in great detail as there are other guides which will walk you through the full details of how to use this technique if you want to do a deep dive. For now, youll want to observe that weve augmented the <code>ggplot</code> with a new element called <code>facet_wrap</code> which takes the ethnicity data column as the basis for rendering separate charts.</p>
<div class="cell">
<div class="sourceCode cell-code" id="cb22"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb22-1"><a href="#cb22-1" aria-hidden="true" tabindex="-1"></a><span class="fu">ggplot</span>(uk_census_2021_religion_ethnicity_nonwhite, <span class="fu">aes</span>(<span class="at">x=</span>C2021_RELIGION_10_NAME, <span class="at">y=</span>OBS_VALUE)) <span class="sc">+</span> </span>
<span id="cb22-2"><a href="#cb22-2" aria-hidden="true" tabindex="-1"></a> <span class="fu">geom_bar</span>(<span class="at">position=</span><span class="st">"dodge"</span>, <span class="at">stat =</span><span class="st">"identity"</span>, <span class="at">colour =</span> <span class="st">"black"</span>) <span class="sc">+</span> </span>
<span id="cb22-3"><a href="#cb22-3" aria-hidden="true" tabindex="-1"></a> <span class="fu">facet_wrap</span>(<span class="sc">~</span>C2021_ETH_8_NAME, <span class="at">ncol =</span> <span class="dv">2</span>) <span class="sc">+</span> <span class="fu">scale_fill_brewer</span>(<span class="at">palette =</span> <span class="st">"Set1"</span>) <span class="sc">+</span> </span>
<span id="cb22-4"><a href="#cb22-4" aria-hidden="true" tabindex="-1"></a> <span class="fu">ggtitle</span>(<span class="st">"Religious Affiliation in the 2021 Census of England and Wales"</span>) <span class="sc">+</span> <span class="fu">xlab</span>(<span class="st">""</span>) <span class="sc">+</span> <span class="fu">ylab</span>(<span class="st">""</span>) <span class="sc">+</span> </span>
<span id="cb22-5"><a href="#cb22-5" aria-hidden="true" tabindex="-1"></a> <span class="fu">theme</span>(<span class="at">axis.text.x =</span> <span class="fu">element_text</span>(<span class="at">angle =</span> <span class="dv">90</span>, <span class="at">vjust =</span> <span class="fl">0.5</span>, <span class="at">hjust=</span><span class="dv">1</span>))</span></code><button title="Copy to Clipboard" class="code-copy-button"><i class="bi"></i></button></pre></div>
<div class="cell-output-display">
<div>
<figure class="figure">
<p><img src="chapter_1_files/figure-html/unnamed-chunk-23-1.png" class="img-fluid figure-img" width="672"></p>
</figure>
</div>
</div>
</div>
<p>Thats a bit better! Now we have a much more accessible set of visual information which compares across categories and renders most of the information were trying to capture.</p>
<p>To take this chart just one step further, Id like to take the faceted chart weve just done and add in totals for the previous two census years (2001 and 2011) so we can see how trends are changing in terms of religious affiliation within ethnic self-identification categories. Well draw on some techniques were already developed above using <code>rbind()</code> to connect up each of these charts (after weve added a column identifying each chart by the census year). We will also need to use one new technique to change the wording of ethnic categories as this isnt consistent from one census to the next and ggplot will struggle to chart things if the terms being used are exactly the same. Well use <code>mutate()</code> again to accomplish this with some slightly different code.</p>
<p>First we need to get the tables of Census 2011 and 2001 religion data from nomis:</p>
<div class="cell">
<div class="sourceCode cell-code" id="cb21"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb21-1"><a href="#cb21-1" aria-hidden="true" tabindex="-1"></a>nomis_extract_census2001 <span class="ot">&lt;-</span> <span class="fu">readRDS</span>(<span class="at">file =</span> (<span class="fu">here</span>(<span class="st">"example_data"</span>, <span class="st">"nomis_extract_census2001.rds"</span>)))</span>
<span id="cb21-2"><a href="#cb21-2" aria-hidden="true" tabindex="-1"></a>nomis_extract_census2011 <span class="ot">&lt;-</span> <span class="fu">readRDS</span>(<span class="at">file =</span> (<span class="fu">here</span>(<span class="st">"example_data"</span>, <span class="st">"nomis_extract_census2011.rds"</span>)))</span></code><button title="Copy to Clipboard" class="code-copy-button"><i class="bi"></i></button></pre></div>
<div class="sourceCode cell-code" id="cb23"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb23-1"><a href="#cb23-1" aria-hidden="true" tabindex="-1"></a>nomis_extract_census2001 <span class="ot">&lt;-</span> <span class="fu">readRDS</span>(<span class="at">file =</span> (<span class="fu">here</span>(<span class="st">"example_data"</span>, <span class="st">"nomis_extract_census2001.rds"</span>)))</span>
<span id="cb23-2"><a href="#cb23-2" aria-hidden="true" tabindex="-1"></a>nomis_extract_census2011 <span class="ot">&lt;-</span> <span class="fu">readRDS</span>(<span class="at">file =</span> (<span class="fu">here</span>(<span class="st">"example_data"</span>, <span class="st">"nomis_extract_census2011.rds"</span>)))</span></code><button title="Copy to Clipboard" class="code-copy-button"><i class="bi"></i></button></pre></div>
</div>
<p>Next, as weve already done above, we need to filter and tidy the tables:</p>
<div class="cell">
<div class="sourceCode cell-code" id="annotated-cell-26"><pre class="sourceCode r code-annotation-code code-with-copy code-annotated"><code class="sourceCode r"><a class="code-annotation-anchor" data-target-cell="annotated-cell-26" data-target-annotation="1" onclick="event.preventDefault();">1</a><span id="annotated-cell-26-1" class="code-annotation-target"><a href="#annotated-cell-26-1" aria-hidden="true" tabindex="-1"></a>uk_census_2001_religion_ethnicity <span class="ot">&lt;-</span> <span class="fu">select</span>(nomis_extract_census2001, GEOGRAPHY_NAME, C_RELPUK11_NAME, C_ETHHUK11_NAME, OBS_VALUE)</span>
<span id="annotated-cell-26-2"><a href="#annotated-cell-26-2" aria-hidden="true" tabindex="-1"></a>uk_census_2011_religion_ethnicity <span class="ot">&lt;-</span> <span class="fu">select</span>(nomis_extract_census2011, GEOGRAPHY_NAME, C_RELPUK11_NAME, C_ETHPUK11_NAME, OBS_VALUE)</span>
<a class="code-annotation-anchor" data-target-cell="annotated-cell-26" data-target-annotation="2" onclick="event.preventDefault();">2</a><span id="annotated-cell-26-3" class="code-annotation-target"><a href="#annotated-cell-26-3" aria-hidden="true" tabindex="-1"></a>uk_census_2001_religion_ethnicity <span class="ot">&lt;-</span> <span class="fu">filter</span>(uk_census_2001_religion_ethnicity, GEOGRAPHY_NAME<span class="sc">==</span><span class="st">"England and Wales"</span> <span class="sc">&amp;</span> C_RELPUK11_NAME <span class="sc">!=</span> <span class="st">"All categories: Religion"</span>)</span>
<span id="annotated-cell-26-4"><a href="#annotated-cell-26-4" aria-hidden="true" tabindex="-1"></a>uk_census_2011_religion_ethnicity <span class="ot">&lt;-</span> <span class="fu">filter</span>(uk_census_2011_religion_ethnicity, GEOGRAPHY_NAME<span class="sc">==</span><span class="st">"England and Wales"</span> <span class="sc">&amp;</span> C_RELPUK11_NAME <span class="sc">!=</span> <span class="st">"All categories: Religion"</span> <span class="sc">&amp;</span> C_ETHPUK11_NAME <span class="sc">!=</span> <span class="st">"All categories: Ethnic group"</span>)</span>
<a class="code-annotation-anchor" data-target-cell="annotated-cell-26" data-target-annotation="3" onclick="event.preventDefault();">3</a><span id="annotated-cell-26-5" class="code-annotation-target"><a href="#annotated-cell-26-5" aria-hidden="true" tabindex="-1"></a>uk_census_2001_religion_ethnicity <span class="ot">&lt;-</span> uk_census_2001_religion_ethnicity <span class="sc">%&gt;%</span> <span class="fu">filter</span>(<span class="fu">grepl</span>(<span class="st">'Total'</span>, C_ETHHUK11_NAME))</span>
<span id="annotated-cell-26-6"><a href="#annotated-cell-26-6" aria-hidden="true" tabindex="-1"></a>uk_census_2011_religion_ethnicity <span class="ot">&lt;-</span> uk_census_2011_religion_ethnicity <span class="sc">%&gt;%</span> <span class="fu">filter</span>(<span class="fu">grepl</span>(<span class="st">'Total'</span>, C_ETHPUK11_NAME))</span>
<span id="annotated-cell-26-7"><a href="#annotated-cell-26-7" aria-hidden="true" tabindex="-1"></a>uk_census_2011_religion_plot <span class="ot">&lt;-</span> <span class="fu">ggplot</span>(uk_census_2011_religion_ethnicity, <span class="fu">aes</span>(<span class="at">x =</span> C_RELPUK11_NAME, <span class="at">y =</span> OBS_VALUE)) <span class="sc">+</span> <span class="fu">geom_bar</span>(<span class="at">stat =</span> <span class="st">"identity"</span>) <span class="sc">+</span> <span class="fu">theme</span>(<span class="at">axis.text.x =</span> <span class="fu">element_text</span>(<span class="at">angle =</span> <span class="dv">90</span>, <span class="at">vjust =</span> <span class="fl">0.5</span>, <span class="at">hjust=</span><span class="dv">1</span>))</span><div class="code-annotation-gutter-bg"></div><div class="code-annotation-gutter"></div></code><button title="Copy to Clipboard" class="code-copy-button"><i class="bi"></i></button></pre></div>
<div class="sourceCode cell-code" id="annotated-cell-28"><pre class="sourceCode r code-annotation-code code-with-copy code-annotated"><code class="sourceCode r"><a class="code-annotation-anchor" data-target-cell="annotated-cell-28" data-target-annotation="1" onclick="event.preventDefault();">1</a><span id="annotated-cell-28-1" class="code-annotation-target"><a href="#annotated-cell-28-1" aria-hidden="true" tabindex="-1"></a>uk_census_2001_religion_ethnicity <span class="ot">&lt;-</span> <span class="fu">select</span>(nomis_extract_census2001, GEOGRAPHY_NAME, C_RELPUK11_NAME, C_ETHHUK11_NAME, OBS_VALUE)</span>
<span id="annotated-cell-28-2"><a href="#annotated-cell-28-2" aria-hidden="true" tabindex="-1"></a>uk_census_2011_religion_ethnicity <span class="ot">&lt;-</span> <span class="fu">select</span>(nomis_extract_census2011, GEOGRAPHY_NAME, C_RELPUK11_NAME, C_ETHPUK11_NAME, OBS_VALUE)</span>
<a class="code-annotation-anchor" data-target-cell="annotated-cell-28" data-target-annotation="2" onclick="event.preventDefault();">2</a><span id="annotated-cell-28-3" class="code-annotation-target"><a href="#annotated-cell-28-3" aria-hidden="true" tabindex="-1"></a>uk_census_2001_religion_ethnicity <span class="ot">&lt;-</span> <span class="fu">filter</span>(uk_census_2001_religion_ethnicity, GEOGRAPHY_NAME<span class="sc">==</span><span class="st">"England and Wales"</span> <span class="sc">&amp;</span> C_RELPUK11_NAME <span class="sc">!=</span> <span class="st">"All categories: Religion"</span>)</span>
<span id="annotated-cell-28-4"><a href="#annotated-cell-28-4" aria-hidden="true" tabindex="-1"></a>uk_census_2011_religion_ethnicity <span class="ot">&lt;-</span> <span class="fu">filter</span>(uk_census_2011_religion_ethnicity, GEOGRAPHY_NAME<span class="sc">==</span><span class="st">"England and Wales"</span> <span class="sc">&amp;</span> C_RELPUK11_NAME <span class="sc">!=</span> <span class="st">"All categories: Religion"</span> <span class="sc">&amp;</span> C_ETHPUK11_NAME <span class="sc">!=</span> <span class="st">"All categories: Ethnic group"</span>)</span>
<a class="code-annotation-anchor" data-target-cell="annotated-cell-28" data-target-annotation="3" onclick="event.preventDefault();">3</a><span id="annotated-cell-28-5" class="code-annotation-target"><a href="#annotated-cell-28-5" aria-hidden="true" tabindex="-1"></a>uk_census_2001_religion_ethnicity <span class="ot">&lt;-</span> uk_census_2001_religion_ethnicity <span class="sc">%&gt;%</span> <span class="fu">filter</span>(<span class="fu">grepl</span>(<span class="st">'Total'</span>, C_ETHHUK11_NAME))</span>
<span id="annotated-cell-28-6"><a href="#annotated-cell-28-6" aria-hidden="true" tabindex="-1"></a>uk_census_2011_religion_ethnicity <span class="ot">&lt;-</span> uk_census_2011_religion_ethnicity <span class="sc">%&gt;%</span> <span class="fu">filter</span>(<span class="fu">grepl</span>(<span class="st">'Total'</span>, C_ETHPUK11_NAME))</span>
<span id="annotated-cell-28-7"><a href="#annotated-cell-28-7" aria-hidden="true" tabindex="-1"></a>uk_census_2011_religion_plot <span class="ot">&lt;-</span> <span class="fu">ggplot</span>(uk_census_2011_religion_ethnicity, <span class="fu">aes</span>(<span class="at">x =</span> C_RELPUK11_NAME, <span class="at">y =</span> OBS_VALUE)) <span class="sc">+</span> <span class="fu">geom_bar</span>(<span class="at">stat =</span> <span class="st">"identity"</span>) <span class="sc">+</span> <span class="fu">theme</span>(<span class="at">axis.text.x =</span> <span class="fu">element_text</span>(<span class="at">angle =</span> <span class="dv">90</span>, <span class="at">vjust =</span> <span class="fl">0.5</span>, <span class="at">hjust=</span><span class="dv">1</span>))</span><div class="code-annotation-gutter-bg"></div><div class="code-annotation-gutter"></div></code><button title="Copy to Clipboard" class="code-copy-button"><i class="bi"></i></button></pre></div>
<div class="cell-annotation">
<dl class="code-annotation-container-grid">
<dt data-target-cell="annotated-cell-26" data-target-annotation="1">1</dt>
<dt data-target-cell="annotated-cell-28" data-target-annotation="1">1</dt>
<dd>
<span data-code-cell="annotated-cell-26" data-code-lines="1,2" data-code-annotation="1">Select columns</span>
<span data-code-cell="annotated-cell-28" data-code-lines="1,2" data-code-annotation="1">Select columns</span>
</dd>
<dt data-target-cell="annotated-cell-26" data-target-annotation="2">2</dt>
<dt data-target-cell="annotated-cell-28" data-target-annotation="2">2</dt>
<dd>
<span data-code-cell="annotated-cell-26" data-code-lines="3,4" data-code-annotation="2">Filter down to simplified dataset with England / Wales and percentages without totals</span>
<span data-code-cell="annotated-cell-28" data-code-lines="3,4" data-code-annotation="2">Filter down to simplified dataset with England / Wales and percentages without totals</span>
</dd>
<dt data-target-cell="annotated-cell-26" data-target-annotation="3">3</dt>
<dt data-target-cell="annotated-cell-28" data-target-annotation="3">3</dt>
<dd>
<span data-code-cell="annotated-cell-26" data-code-lines="5,6" data-code-annotation="3">Drop unnecessary columns</span>
<span data-code-cell="annotated-cell-28" data-code-lines="5,6" data-code-annotation="3">Drop unnecessary columns</span>
</dd>
</dl>
</div>
</div>
<p>The <code>bind</code> tool were going to use is very picky and expects everything to match perfectly so that it dont join up data that is unrelated. Unfortunately, the census table data format has changed in each decade, so we need to harmonise the column titles so that we can join the data and avoid confusing R.</p>
<p>The <code>bind</code> tool were going to use is very picky and expects everything to match perfectly so that it doesnt join up data that is unrelated. Unfortunately, the census table data format has changed in each decade, so we need to harmonise the column titles so that we can join the data and avoid confusing R. This is a pretty common problem youll face in working with multiple datasets in the same chart, so well worth noticing the extra necessary step here.</p>
<div class="cell">
<div class="sourceCode cell-code" id="annotated-cell-27"><pre class="sourceCode r code-annotation-code code-with-copy code-annotated"><code class="sourceCode r"><a class="code-annotation-anchor" data-target-cell="annotated-cell-27" data-target-annotation="1" onclick="event.preventDefault();">1</a><span id="annotated-cell-27-1" class="code-annotation-target"><a href="#annotated-cell-27-1" aria-hidden="true" tabindex="-1"></a>uk_census_2001_religion_ethnicity<span class="sc">$</span>dataset <span class="ot">&lt;-</span> <span class="fu">c</span>(<span class="st">"2001"</span>)</span>
<span id="annotated-cell-27-2"><a href="#annotated-cell-27-2" aria-hidden="true" tabindex="-1"></a>uk_census_2011_religion_ethnicity<span class="sc">$</span>dataset <span class="ot">&lt;-</span> <span class="fu">c</span>(<span class="st">"2011"</span>)</span>
<span id="annotated-cell-27-3"><a href="#annotated-cell-27-3" aria-hidden="true" tabindex="-1"></a>uk_census_2021_religion_ethnicity<span class="sc">$</span>dataset <span class="ot">&lt;-</span> <span class="fu">c</span>(<span class="st">"2021"</span>)</span>
<span id="annotated-cell-27-4"><a href="#annotated-cell-27-4" aria-hidden="true" tabindex="-1"></a></span>
<a class="code-annotation-anchor" data-target-cell="annotated-cell-27" data-target-annotation="2" onclick="event.preventDefault();">2</a><span id="annotated-cell-27-5" class="code-annotation-target"><a href="#annotated-cell-27-5" aria-hidden="true" tabindex="-1"></a><span class="fu">names</span>(uk_census_2001_religion_ethnicity) <span class="ot">&lt;-</span> <span class="fu">c</span>(<span class="st">"Geography"</span>, <span class="st">"Religion"</span>, <span class="st">"Ethnicity"</span>, <span class="st">"Value"</span>, <span class="st">"Year"</span>)</span>
<span id="annotated-cell-27-6"><a href="#annotated-cell-27-6" aria-hidden="true" tabindex="-1"></a><span class="fu">names</span>(uk_census_2011_religion_ethnicity) <span class="ot">&lt;-</span> <span class="fu">c</span>(<span class="st">"Geography"</span>, <span class="st">"Religion"</span>, <span class="st">"Ethnicity"</span>, <span class="st">"Value"</span>, <span class="st">"Year"</span>)</span>
<span id="annotated-cell-27-7"><a href="#annotated-cell-27-7" aria-hidden="true" tabindex="-1"></a><span class="fu">names</span>(uk_census_2021_religion_ethnicity) <span class="ot">&lt;-</span> <span class="fu">c</span>(<span class="st">"Geography"</span>, <span class="st">"Religion"</span>, <span class="st">"Ethnicity"</span>, <span class="st">"Value"</span>, <span class="st">"Year"</span>)</span><div class="code-annotation-gutter-bg"></div><div class="code-annotation-gutter"></div></code><button title="Copy to Clipboard" class="code-copy-button"><i class="bi"></i></button></pre></div>
<div class="sourceCode cell-code" id="annotated-cell-29"><pre class="sourceCode r code-annotation-code code-with-copy code-annotated"><code class="sourceCode r"><a class="code-annotation-anchor" data-target-cell="annotated-cell-29" data-target-annotation="1" onclick="event.preventDefault();">1</a><span id="annotated-cell-29-1" class="code-annotation-target"><a href="#annotated-cell-29-1" aria-hidden="true" tabindex="-1"></a>uk_census_2001_religion_ethnicity<span class="sc">$</span>dataset <span class="ot">&lt;-</span> <span class="fu">c</span>(<span class="st">"2001"</span>)</span>
<span id="annotated-cell-29-2"><a href="#annotated-cell-29-2" aria-hidden="true" tabindex="-1"></a>uk_census_2011_religion_ethnicity<span class="sc">$</span>dataset <span class="ot">&lt;-</span> <span class="fu">c</span>(<span class="st">"2011"</span>)</span>
<span id="annotated-cell-29-3"><a href="#annotated-cell-29-3" aria-hidden="true" tabindex="-1"></a>uk_census_2021_religion_ethnicity<span class="sc">$</span>dataset <span class="ot">&lt;-</span> <span class="fu">c</span>(<span class="st">"2021"</span>)</span>
<span id="annotated-cell-29-4"><a href="#annotated-cell-29-4" aria-hidden="true" tabindex="-1"></a></span>
<a class="code-annotation-anchor" data-target-cell="annotated-cell-29" data-target-annotation="2" onclick="event.preventDefault();">2</a><span id="annotated-cell-29-5" class="code-annotation-target"><a href="#annotated-cell-29-5" aria-hidden="true" tabindex="-1"></a><span class="fu">names</span>(uk_census_2001_religion_ethnicity) <span class="ot">&lt;-</span> <span class="fu">c</span>(<span class="st">"Geography"</span>, <span class="st">"Religion"</span>, <span class="st">"Ethnicity"</span>, <span class="st">"Value"</span>, <span class="st">"Year"</span>)</span>
<span id="annotated-cell-29-6"><a href="#annotated-cell-29-6" aria-hidden="true" tabindex="-1"></a><span class="fu">names</span>(uk_census_2011_religion_ethnicity) <span class="ot">&lt;-</span> <span class="fu">c</span>(<span class="st">"Geography"</span>, <span class="st">"Religion"</span>, <span class="st">"Ethnicity"</span>, <span class="st">"Value"</span>, <span class="st">"Year"</span>)</span>
<span id="annotated-cell-29-7"><a href="#annotated-cell-29-7" aria-hidden="true" tabindex="-1"></a><span class="fu">names</span>(uk_census_2021_religion_ethnicity) <span class="ot">&lt;-</span> <span class="fu">c</span>(<span class="st">"Geography"</span>, <span class="st">"Religion"</span>, <span class="st">"Ethnicity"</span>, <span class="st">"Value"</span>, <span class="st">"Year"</span>)</span><div class="code-annotation-gutter-bg"></div><div class="code-annotation-gutter"></div></code><button title="Copy to Clipboard" class="code-copy-button"><i class="bi"></i></button></pre></div>
<div class="cell-annotation">
<dl class="code-annotation-container-grid">
<dt data-target-cell="annotated-cell-27" data-target-annotation="1">1</dt>
<dt data-target-cell="annotated-cell-29" data-target-annotation="1">1</dt>
<dd>
<span data-code-cell="annotated-cell-27" data-code-lines="1,2,3" data-code-annotation="1">First we add a column to each dataframe letting us know which census year it is from so we dont lose track of the census it comes from when theyre all combined into a single table.</span>
<span data-code-cell="annotated-cell-29" data-code-lines="1,2,3" data-code-annotation="1">First we add a column to each dataframe letting us know which census year it is from so we dont lose track of the census it comes from when theyre all combined into a single table.</span>
</dd>
<dt data-target-cell="annotated-cell-27" data-target-annotation="2">2</dt>
<dt data-target-cell="annotated-cell-29" data-target-annotation="2">2</dt>
<dd>
<span data-code-cell="annotated-cell-27" data-code-lines="5,6,7" data-code-annotation="2">Next, we tidy the <code>names</code> of each column by overwriting them all with more legible versions.</span>
<span data-code-cell="annotated-cell-29" data-code-lines="5,6,7" data-code-annotation="2">Next, we tidy the <code>names</code> of each column by overwriting them all with more legible versions.</span>
</dd>
</dl>
</div>
</div>
<p>Now that we have column titles all sorted, we also need to adjust the category descriptions as the formatting has also changed in subsequent decades. To do this, well use the very handy tool <code>mutate</code> which is a bit like a “find and replace text” tool in R:</p>
<div class="cell">
<div class="sourceCode cell-code" id="cb22"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb22-1"><a href="#cb22-1" aria-hidden="true" tabindex="-1"></a><span class="co"># Next we need to change the terms using mutate()</span></span>
<span id="cb22-2"><a href="#cb22-2" aria-hidden="true" tabindex="-1"></a>uk_census_2001_religion_ethnicity <span class="ot">&lt;-</span> uk_census_2001_religion_ethnicity <span class="sc">%&gt;%</span> </span>
<span id="cb22-3"><a href="#cb22-3" aria-hidden="true" tabindex="-1"></a> <span class="fu">mutate</span>(<span class="at">Ethnicity =</span> <span class="fu">str_replace_all</span>(Ethnicity, </span>
<span id="cb22-4"><a href="#cb22-4" aria-hidden="true" tabindex="-1"></a> <span class="at">pattern =</span> <span class="st">"^White: Total$"</span>, <span class="at">replacement =</span> <span class="st">"White"</span>)) <span class="sc">%&gt;%</span></span>
<span id="cb22-5"><a href="#cb22-5" aria-hidden="true" tabindex="-1"></a> <span class="fu">mutate</span>(<span class="at">Ethnicity =</span> <span class="fu">str_replace_all</span>(Ethnicity, </span>
<span id="cb22-6"><a href="#cb22-6" aria-hidden="true" tabindex="-1"></a> <span class="at">pattern =</span> <span class="st">"^Mixed: Total$"</span>, <span class="at">replacement =</span> <span class="st">"Mixed"</span>)) <span class="sc">%&gt;%</span></span>
<span id="cb22-7"><a href="#cb22-7" aria-hidden="true" tabindex="-1"></a> <span class="fu">mutate</span>(<span class="at">Ethnicity =</span> <span class="fu">str_replace_all</span>(Ethnicity, </span>
<span id="cb22-8"><a href="#cb22-8" aria-hidden="true" tabindex="-1"></a> <span class="at">pattern =</span> <span class="st">"^Asian: Total$"</span>, <span class="at">replacement =</span> <span class="st">"Asian"</span>)) <span class="sc">%&gt;%</span></span>
<span id="cb22-9"><a href="#cb22-9" aria-hidden="true" tabindex="-1"></a> <span class="fu">mutate</span>(<span class="at">Ethnicity =</span> <span class="fu">str_replace_all</span>(Ethnicity, </span>
<span id="cb22-10"><a href="#cb22-10" aria-hidden="true" tabindex="-1"></a> <span class="at">pattern =</span> <span class="st">"^Black or Black British: Total$"</span>, <span class="at">replacement =</span> <span class="st">"Black"</span>)) <span class="sc">%&gt;%</span></span>
<span id="cb22-11"><a href="#cb22-11" aria-hidden="true" tabindex="-1"></a> <span class="fu">mutate</span>(<span class="at">Ethnicity =</span> <span class="fu">str_replace_all</span>(Ethnicity, </span>
<span id="cb22-12"><a href="#cb22-12" aria-hidden="true" tabindex="-1"></a> <span class="at">pattern =</span> <span class="st">"^Chinese or Other ethnic group: Total$"</span>, <span class="at">replacement =</span> <span class="st">"Other"</span>))</span>
<span id="cb22-13"><a href="#cb22-13" aria-hidden="true" tabindex="-1"></a> </span>
<span id="cb22-14"><a href="#cb22-14" aria-hidden="true" tabindex="-1"></a>uk_census_2011_religion_ethnicity <span class="ot">&lt;-</span> uk_census_2011_religion_ethnicity <span class="sc">%&gt;%</span> </span>
<span id="cb22-15"><a href="#cb22-15" aria-hidden="true" tabindex="-1"></a> <span class="fu">mutate</span>(<span class="at">Ethnicity =</span> <span class="fu">str_replace_all</span>(Ethnicity, </span>
<span id="cb22-16"><a href="#cb22-16" aria-hidden="true" tabindex="-1"></a> <span class="at">pattern =</span> <span class="st">"^White: Total$"</span>, <span class="at">replacement =</span> <span class="st">"White"</span>)) <span class="sc">%&gt;%</span></span>
<span id="cb22-17"><a href="#cb22-17" aria-hidden="true" tabindex="-1"></a> <span class="fu">mutate</span>(<span class="at">Ethnicity =</span> <span class="fu">str_replace_all</span>(Ethnicity, </span>
<span id="cb22-18"><a href="#cb22-18" aria-hidden="true" tabindex="-1"></a> <span class="at">pattern =</span> <span class="st">"^Mixed/multiple ethnic group: Total$"</span>, <span class="at">replacement =</span> <span class="st">"Mixed"</span>)) <span class="sc">%&gt;%</span></span>
<span id="cb22-19"><a href="#cb22-19" aria-hidden="true" tabindex="-1"></a> <span class="fu">mutate</span>(<span class="at">Ethnicity =</span> <span class="fu">str_replace_all</span>(Ethnicity, </span>
<span id="cb22-20"><a href="#cb22-20" aria-hidden="true" tabindex="-1"></a> <span class="at">pattern =</span> <span class="st">"^Asian/Asian British: Total$"</span>, <span class="at">replacement =</span> <span class="st">"Asian"</span>)) <span class="sc">%&gt;%</span></span>
<span id="cb22-21"><a href="#cb22-21" aria-hidden="true" tabindex="-1"></a> <span class="fu">mutate</span>(<span class="at">Ethnicity =</span> <span class="fu">str_replace_all</span>(Ethnicity, </span>
<span id="cb22-22"><a href="#cb22-22" aria-hidden="true" tabindex="-1"></a> <span class="at">pattern =</span> <span class="st">"^Black/African/Caribbean/Black British: Total$"</span>, <span class="at">replacement =</span> <span class="st">"Black"</span>)) <span class="sc">%&gt;%</span></span>
<span id="cb22-23"><a href="#cb22-23" aria-hidden="true" tabindex="-1"></a> <span class="fu">mutate</span>(<span class="at">Ethnicity =</span> <span class="fu">str_replace_all</span>(Ethnicity, </span>
<span id="cb22-24"><a href="#cb22-24" aria-hidden="true" tabindex="-1"></a> <span class="at">pattern =</span> <span class="st">"^Other ethnic group: Total$"</span>, <span class="at">replacement =</span> <span class="st">"Other"</span>))</span>
<span id="cb22-25"><a href="#cb22-25" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb22-26"><a href="#cb22-26" aria-hidden="true" tabindex="-1"></a>uk_census_2021_religion_ethnicity <span class="ot">&lt;-</span> uk_census_2021_religion_ethnicity <span class="sc">%&gt;%</span> </span>
<span id="cb22-27"><a href="#cb22-27" aria-hidden="true" tabindex="-1"></a> <span class="fu">mutate</span>(<span class="at">Ethnicity =</span> <span class="fu">str_replace_all</span>(Ethnicity, </span>
<span id="cb22-28"><a href="#cb22-28" aria-hidden="true" tabindex="-1"></a> <span class="at">pattern =</span> <span class="st">"^White: Total$"</span>, <span class="at">replacement =</span> <span class="st">"White"</span>)) <span class="sc">%&gt;%</span></span>
<span id="cb22-29"><a href="#cb22-29" aria-hidden="true" tabindex="-1"></a> <span class="fu">mutate</span>(<span class="at">Ethnicity =</span> <span class="fu">str_replace_all</span>(Ethnicity, </span>
<span id="cb22-30"><a href="#cb22-30" aria-hidden="true" tabindex="-1"></a> <span class="at">pattern =</span> <span class="st">"^Mixed or Multiple ethnic groups$"</span>, <span class="at">replacement =</span> <span class="st">"Mixed"</span>)) <span class="sc">%&gt;%</span></span>
<span id="cb22-31"><a href="#cb22-31" aria-hidden="true" tabindex="-1"></a> <span class="fu">mutate</span>(<span class="at">Ethnicity =</span> <span class="fu">str_replace_all</span>(Ethnicity, </span>
<span id="cb22-32"><a href="#cb22-32" aria-hidden="true" tabindex="-1"></a> <span class="at">pattern =</span> <span class="st">"^Asian, Asian British or Asian Welsh$"</span>, <span class="at">replacement =</span> <span class="st">"Asian"</span>)) <span class="sc">%&gt;%</span></span>
<span id="cb22-33"><a href="#cb22-33" aria-hidden="true" tabindex="-1"></a> <span class="fu">mutate</span>(<span class="at">Ethnicity =</span> <span class="fu">str_replace_all</span>(Ethnicity, </span>
<span id="cb22-34"><a href="#cb22-34" aria-hidden="true" tabindex="-1"></a> <span class="at">pattern =</span> <span class="st">"^Black, Black British, Black Welsh, Caribbean or African$"</span>, <span class="at">replacement =</span> <span class="st">"Black"</span>)) <span class="sc">%&gt;%</span></span>
<span id="cb22-35"><a href="#cb22-35" aria-hidden="true" tabindex="-1"></a> <span class="fu">mutate</span>(<span class="at">Ethnicity =</span> <span class="fu">str_replace_all</span>(Ethnicity, </span>
<span id="cb22-36"><a href="#cb22-36" aria-hidden="true" tabindex="-1"></a> <span class="at">pattern =</span> <span class="st">"^Other ethnic group$"</span>, <span class="at">replacement =</span> <span class="st">"Other"</span>))</span></code><button title="Copy to Clipboard" class="code-copy-button"><i class="bi"></i></button></pre></div>
<div class="sourceCode cell-code" id="cb24"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb24-1"><a href="#cb24-1" aria-hidden="true" tabindex="-1"></a><span class="co"># Next we need to change the terms using mutate()</span></span>
<span id="cb24-2"><a href="#cb24-2" aria-hidden="true" tabindex="-1"></a>uk_census_2001_religion_ethnicity <span class="ot">&lt;-</span> uk_census_2001_religion_ethnicity <span class="sc">%&gt;%</span> </span>
<span id="cb24-3"><a href="#cb24-3" aria-hidden="true" tabindex="-1"></a> <span class="fu">mutate</span>(<span class="at">Ethnicity =</span> <span class="fu">str_replace_all</span>(Ethnicity, </span>
<span id="cb24-4"><a href="#cb24-4" aria-hidden="true" tabindex="-1"></a> <span class="at">pattern =</span> <span class="st">"^White: Total$"</span>, <span class="at">replacement =</span> <span class="st">"White"</span>)) <span class="sc">%&gt;%</span></span>
<span id="cb24-5"><a href="#cb24-5" aria-hidden="true" tabindex="-1"></a> <span class="fu">mutate</span>(<span class="at">Ethnicity =</span> <span class="fu">str_replace_all</span>(Ethnicity, </span>
<span id="cb24-6"><a href="#cb24-6" aria-hidden="true" tabindex="-1"></a> <span class="at">pattern =</span> <span class="st">"^Mixed: Total$"</span>, <span class="at">replacement =</span> <span class="st">"Mixed"</span>)) <span class="sc">%&gt;%</span></span>
<span id="cb24-7"><a href="#cb24-7" aria-hidden="true" tabindex="-1"></a> <span class="fu">mutate</span>(<span class="at">Ethnicity =</span> <span class="fu">str_replace_all</span>(Ethnicity, </span>
<span id="cb24-8"><a href="#cb24-8" aria-hidden="true" tabindex="-1"></a> <span class="at">pattern =</span> <span class="st">"^Asian: Total$"</span>, <span class="at">replacement =</span> <span class="st">"Asian"</span>)) <span class="sc">%&gt;%</span></span>
<span id="cb24-9"><a href="#cb24-9" aria-hidden="true" tabindex="-1"></a> <span class="fu">mutate</span>(<span class="at">Ethnicity =</span> <span class="fu">str_replace_all</span>(Ethnicity, </span>
<span id="cb24-10"><a href="#cb24-10" aria-hidden="true" tabindex="-1"></a> <span class="at">pattern =</span> <span class="st">"^Black or Black British: Total$"</span>, <span class="at">replacement =</span> <span class="st">"Black"</span>)) <span class="sc">%&gt;%</span></span>
<span id="cb24-11"><a href="#cb24-11" aria-hidden="true" tabindex="-1"></a> <span class="fu">mutate</span>(<span class="at">Ethnicity =</span> <span class="fu">str_replace_all</span>(Ethnicity, </span>
<span id="cb24-12"><a href="#cb24-12" aria-hidden="true" tabindex="-1"></a> <span class="at">pattern =</span> <span class="st">"^Chinese or Other ethnic group: Total$"</span>, <span class="at">replacement =</span> <span class="st">"Other"</span>))</span>
<span id="cb24-13"><a href="#cb24-13" aria-hidden="true" tabindex="-1"></a> </span>
<span id="cb24-14"><a href="#cb24-14" aria-hidden="true" tabindex="-1"></a>uk_census_2011_religion_ethnicity <span class="ot">&lt;-</span> uk_census_2011_religion_ethnicity <span class="sc">%&gt;%</span> </span>
<span id="cb24-15"><a href="#cb24-15" aria-hidden="true" tabindex="-1"></a> <span class="fu">mutate</span>(<span class="at">Ethnicity =</span> <span class="fu">str_replace_all</span>(Ethnicity, </span>
<span id="cb24-16"><a href="#cb24-16" aria-hidden="true" tabindex="-1"></a> <span class="at">pattern =</span> <span class="st">"^White: Total$"</span>, <span class="at">replacement =</span> <span class="st">"White"</span>)) <span class="sc">%&gt;%</span></span>
<span id="cb24-17"><a href="#cb24-17" aria-hidden="true" tabindex="-1"></a> <span class="fu">mutate</span>(<span class="at">Ethnicity =</span> <span class="fu">str_replace_all</span>(Ethnicity, </span>
<span id="cb24-18"><a href="#cb24-18" aria-hidden="true" tabindex="-1"></a> <span class="at">pattern =</span> <span class="st">"^Mixed/multiple ethnic group: Total$"</span>, <span class="at">replacement =</span> <span class="st">"Mixed"</span>)) <span class="sc">%&gt;%</span></span>
<span id="cb24-19"><a href="#cb24-19" aria-hidden="true" tabindex="-1"></a> <span class="fu">mutate</span>(<span class="at">Ethnicity =</span> <span class="fu">str_replace_all</span>(Ethnicity, </span>
<span id="cb24-20"><a href="#cb24-20" aria-hidden="true" tabindex="-1"></a> <span class="at">pattern =</span> <span class="st">"^Asian/Asian British: Total$"</span>, <span class="at">replacement =</span> <span class="st">"Asian"</span>)) <span class="sc">%&gt;%</span></span>
<span id="cb24-21"><a href="#cb24-21" aria-hidden="true" tabindex="-1"></a> <span class="fu">mutate</span>(<span class="at">Ethnicity =</span> <span class="fu">str_replace_all</span>(Ethnicity, </span>
<span id="cb24-22"><a href="#cb24-22" aria-hidden="true" tabindex="-1"></a> <span class="at">pattern =</span> <span class="st">"^Black/African/Caribbean/Black British: Total$"</span>, <span class="at">replacement =</span> <span class="st">"Black"</span>)) <span class="sc">%&gt;%</span></span>
<span id="cb24-23"><a href="#cb24-23" aria-hidden="true" tabindex="-1"></a> <span class="fu">mutate</span>(<span class="at">Ethnicity =</span> <span class="fu">str_replace_all</span>(Ethnicity, </span>
<span id="cb24-24"><a href="#cb24-24" aria-hidden="true" tabindex="-1"></a> <span class="at">pattern =</span> <span class="st">"^Other ethnic group: Total$"</span>, <span class="at">replacement =</span> <span class="st">"Other"</span>))</span>
<span id="cb24-25"><a href="#cb24-25" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb24-26"><a href="#cb24-26" aria-hidden="true" tabindex="-1"></a>uk_census_2021_religion_ethnicity <span class="ot">&lt;-</span> uk_census_2021_religion_ethnicity <span class="sc">%&gt;%</span> </span>
<span id="cb24-27"><a href="#cb24-27" aria-hidden="true" tabindex="-1"></a> <span class="fu">mutate</span>(<span class="at">Ethnicity =</span> <span class="fu">str_replace_all</span>(Ethnicity, </span>
<span id="cb24-28"><a href="#cb24-28" aria-hidden="true" tabindex="-1"></a> <span class="at">pattern =</span> <span class="st">"^White: Total$"</span>, <span class="at">replacement =</span> <span class="st">"White"</span>)) <span class="sc">%&gt;%</span></span>
<span id="cb24-29"><a href="#cb24-29" aria-hidden="true" tabindex="-1"></a> <span class="fu">mutate</span>(<span class="at">Ethnicity =</span> <span class="fu">str_replace_all</span>(Ethnicity, </span>
<span id="cb24-30"><a href="#cb24-30" aria-hidden="true" tabindex="-1"></a> <span class="at">pattern =</span> <span class="st">"^Mixed or Multiple ethnic groups$"</span>, <span class="at">replacement =</span> <span class="st">"Mixed"</span>)) <span class="sc">%&gt;%</span></span>
<span id="cb24-31"><a href="#cb24-31" aria-hidden="true" tabindex="-1"></a> <span class="fu">mutate</span>(<span class="at">Ethnicity =</span> <span class="fu">str_replace_all</span>(Ethnicity, </span>
<span id="cb24-32"><a href="#cb24-32" aria-hidden="true" tabindex="-1"></a> <span class="at">pattern =</span> <span class="st">"^Asian, Asian British or Asian Welsh$"</span>, <span class="at">replacement =</span> <span class="st">"Asian"</span>)) <span class="sc">%&gt;%</span></span>
<span id="cb24-33"><a href="#cb24-33" aria-hidden="true" tabindex="-1"></a> <span class="fu">mutate</span>(<span class="at">Ethnicity =</span> <span class="fu">str_replace_all</span>(Ethnicity, </span>
<span id="cb24-34"><a href="#cb24-34" aria-hidden="true" tabindex="-1"></a> <span class="at">pattern =</span> <span class="st">"^Black, Black British, Black Welsh, Caribbean or African$"</span>, <span class="at">replacement =</span> <span class="st">"Black"</span>)) <span class="sc">%&gt;%</span></span>
<span id="cb24-35"><a href="#cb24-35" aria-hidden="true" tabindex="-1"></a> <span class="fu">mutate</span>(<span class="at">Ethnicity =</span> <span class="fu">str_replace_all</span>(Ethnicity, </span>
<span id="cb24-36"><a href="#cb24-36" aria-hidden="true" tabindex="-1"></a> <span class="at">pattern =</span> <span class="st">"^Other ethnic group$"</span>, <span class="at">replacement =</span> <span class="st">"Other"</span>))</span></code><button title="Copy to Clipboard" class="code-copy-button"><i class="bi"></i></button></pre></div>
</div>
<p>Now that we have all the columns and data in formats which will match for merge, letd do the merge! This is only two (rather than three operations) as we combine 2021 and 2011 and then do a second combine that grafts in the 2001 data:</p>
<div class="cell">
<div class="sourceCode cell-code" id="cb23"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb23-1"><a href="#cb23-1" aria-hidden="true" tabindex="-1"></a>uk_census_merged_religion_ethnicity <span class="ot">&lt;-</span> <span class="fu">rbind</span>(uk_census_2021_religion_ethnicity, uk_census_2011_religion_ethnicity)</span>
<span id="cb23-2"><a href="#cb23-2" aria-hidden="true" tabindex="-1"></a>uk_census_merged_religion_ethnicity <span class="ot">&lt;-</span> <span class="fu">rbind</span>(uk_census_merged_religion_ethnicity, uk_census_2001_religion_ethnicity)</span></code><button title="Copy to Clipboard" class="code-copy-button"><i class="bi"></i></button></pre></div>
<div class="sourceCode cell-code" id="cb25"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb25-1"><a href="#cb25-1" aria-hidden="true" tabindex="-1"></a>uk_census_merged_religion_ethnicity <span class="ot">&lt;-</span> <span class="fu">rbind</span>(uk_census_2021_religion_ethnicity, uk_census_2011_religion_ethnicity)</span>
<span id="cb25-2"><a href="#cb25-2" aria-hidden="true" tabindex="-1"></a>uk_census_merged_religion_ethnicity <span class="ot">&lt;-</span> <span class="fu">rbind</span>(uk_census_merged_religion_ethnicity, uk_census_2001_religion_ethnicity)</span></code><button title="Copy to Clipboard" class="code-copy-button"><i class="bi"></i></button></pre></div>
</div>
<p>As we realised in the work above, we need to split out non-white and white data so that the data is visually comprehensible:</p>
<div class="cell">
<div class="sourceCode cell-code" id="cb24"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb24-1"><a href="#cb24-1" aria-hidden="true" tabindex="-1"></a>uk_census_merged_religion_ethnicity_nonwhite <span class="ot">&lt;-</span> <span class="fu">filter</span>(uk_census_merged_religion_ethnicity, Ethnicity <span class="sc">!=</span> <span class="st">"White"</span>)</span></code><button title="Copy to Clipboard" class="code-copy-button"><i class="bi"></i></button></pre></div>
<div class="sourceCode cell-code" id="cb26"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb26-1"><a href="#cb26-1" aria-hidden="true" tabindex="-1"></a>uk_census_merged_religion_ethnicity_nonwhite <span class="ot">&lt;-</span> <span class="fu">filter</span>(uk_census_merged_religion_ethnicity, Ethnicity <span class="sc">!=</span> <span class="st">"White"</span>)</span></code><button title="Copy to Clipboard" class="code-copy-button"><i class="bi"></i></button></pre></div>
</div>
<p>Hopefully if everything went properly, we can now do an initial <code>ggplot</code> to see how things look side-by-side:</p>
<div class="cell">
<div class="sourceCode cell-code" id="cb25"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb25-1"><a href="#cb25-1" aria-hidden="true" tabindex="-1"></a><span class="fu">ggplot</span>(uk_census_merged_religion_ethnicity_nonwhite, <span class="fu">aes</span>(<span class="at">fill=</span>Year, <span class="at">x=</span>Religion, <span class="at">y=</span>Value)) <span class="sc">+</span> <span class="fu">geom_bar</span>(<span class="at">position=</span><span class="st">"dodge"</span>, <span class="at">stat =</span><span class="st">"identity"</span>, <span class="at">colour =</span> <span class="st">"black"</span>) <span class="sc">+</span> <span class="fu">facet_wrap</span>(<span class="sc">~</span>Ethnicity, <span class="at">ncol =</span> <span class="dv">2</span>) <span class="sc">+</span> <span class="fu">scale_fill_brewer</span>(<span class="at">palette =</span> <span class="st">"Set1"</span>) <span class="sc">+</span> <span class="fu">ggtitle</span>(<span class="st">"Religious Affiliation in the 2001-2021 Census of England and Wales"</span>) <span class="sc">+</span> <span class="fu">xlab</span>(<span class="st">""</span>) <span class="sc">+</span> <span class="fu">ylab</span>(<span class="st">""</span>) <span class="sc">+</span> <span class="fu">theme</span>(<span class="at">axis.text.x =</span> <span class="fu">element_text</span>(<span class="at">angle =</span> <span class="dv">90</span>, <span class="at">vjust =</span> <span class="fl">0.5</span>, <span class="at">hjust=</span><span class="dv">1</span>))</span></code><button title="Copy to Clipboard" class="code-copy-button"><i class="bi"></i></button></pre></div>
<div class="cell-output-display">
<div>
<figure class="figure">
<p><img src="chapter_1_files/figure-html/unnamed-chunk-28-1.png" class="img-fluid figure-img" width="672"></p>
</figure>
</div>
</div>
</div>
<p>Were getting there, but as you can see there are a few formatting issues which remain. Our y-axis number labels are in scientific format which isnt easy to read. You can use the very powerful and flexible <code>scales()</code> library to bring in some more readable formatting of numbers in a variety of places in R including in ggplot visualizations.</p>
<div class="cell">
<div class="sourceCode cell-code" id="cb26"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb26-1"><a href="#cb26-1" aria-hidden="true" tabindex="-1"></a><span class="fu">library</span>(scales) <span class="sc">|&gt;</span> <span class="fu">suppressPackageStartupMessages</span>()</span>
<span id="cb26-2"><a href="#cb26-2" aria-hidden="true" tabindex="-1"></a><span class="fu">ggplot</span>(uk_census_merged_religion_ethnicity_nonwhite, <span class="fu">aes</span>(<span class="at">fill=</span>Year, <span class="at">x=</span>Religion, <span class="at">y=</span>Value)) <span class="sc">+</span> <span class="fu">geom_bar</span>(<span class="at">position=</span><span class="st">"dodge"</span>, <span class="at">stat =</span><span class="st">"identity"</span>, <span class="at">colour =</span> <span class="st">"black"</span>) <span class="sc">+</span> <span class="fu">facet_wrap</span>(<span class="sc">~</span>Ethnicity, <span class="at">ncol =</span> <span class="dv">2</span>) <span class="sc">+</span> <span class="fu">scale_fill_brewer</span>(<span class="at">palette =</span> <span class="st">"Set1"</span>) <span class="sc">+</span> <span class="fu">scale_y_continuous</span>(<span class="at">labels =</span> <span class="fu">unit_format</span>(<span class="at">unit =</span> <span class="st">"M"</span>, <span class="at">scale =</span> <span class="fl">1e-6</span>), <span class="at">breaks =</span> <span class="fu">breaks_extended</span>(<span class="dv">8</span>)) <span class="sc">+</span> <span class="fu">ggtitle</span>(<span class="st">"Religious Affiliation in the 2001-2021 Census of England and Wales"</span>) <span class="sc">+</span> <span class="fu">xlab</span>(<span class="st">""</span>) <span class="sc">+</span> <span class="fu">ylab</span>(<span class="st">""</span>) <span class="sc">+</span> <span class="fu">theme</span>(<span class="at">axis.text.x =</span> <span class="fu">element_text</span>(<span class="at">angle =</span> <span class="dv">90</span>, <span class="at">vjust =</span> <span class="fl">0.5</span>, <span class="at">hjust=</span><span class="dv">1</span>))</span></code><button title="Copy to Clipboard" class="code-copy-button"><i class="bi"></i></button></pre></div>
<div class="cell-output-display">
<div>
<figure class="figure">
<p><img src="chapter_1_files/figure-html/unnamed-chunk-29-1.png" class="img-fluid figure-img" width="672"></p>
</figure>
</div>
</div>
</div>
<p>This chart shows an increase in almost every category for each decade, though its a bit hard to read in some cases. However, if we attend to our hacker principles, theres another element here which can produce some misleading information. Consider for a moment how this information is based on the increase in <em>raw numbers</em>. Its possbile that the numbers for each religion category may be going up, but population levels are also rising, and its possible here that the percentage share for a particular category may have gone up a bit less than population increase, e.g.&nbsp;the share of the population for that category has actually gone <em>down</em>. This is easy to fix and provide some more accurate information by normalising those figures based on the share of overall population for each decade. Lets transform and visualise our data as percentages to see what kind of trends we can actually isolate:</p>
<div class="cell">
<div class="sourceCode cell-code" id="cb27"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb27-1"><a href="#cb27-1" aria-hidden="true" tabindex="-1"></a>uk_census_merged_religion_ethnicity <span class="ot">&lt;-</span> uk_census_merged_religion_ethnicity <span class="sc">%&gt;%</span></span>
<span id="cb27-2"><a href="#cb27-2" aria-hidden="true" tabindex="-1"></a> <span class="fu">group_by</span>(Ethnicity, Year) <span class="sc">%&gt;%</span></span>
<span id="cb27-3"><a href="#cb27-3" aria-hidden="true" tabindex="-1"></a> dplyr<span class="sc">::</span><span class="fu">mutate</span>(<span class="at">Percent =</span> Value<span class="sc">/</span><span class="fu">sum</span>(Value))</span>
<span id="cb27-4"><a href="#cb27-4" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb27-5"><a href="#cb27-5" aria-hidden="true" tabindex="-1"></a><span class="fu">ggplot</span>(uk_census_merged_religion_ethnicity, <span class="fu">aes</span>(<span class="at">fill=</span>Year, <span class="at">x=</span>Religion, <span class="at">y=</span>Percent)) <span class="sc">+</span> <span class="fu">geom_bar</span>(<span class="at">position=</span><span class="st">"dodge"</span>, <span class="at">stat =</span><span class="st">"identity"</span>, <span class="at">colour =</span> <span class="st">"black"</span>) <span class="sc">+</span> <span class="fu">facet_wrap</span>(<span class="sc">~</span>Ethnicity, <span class="at">scales=</span><span class="st">"free_x"</span>) <span class="sc">+</span> <span class="fu">scale_fill_brewer</span>(<span class="at">palette =</span> <span class="st">"Set1"</span>) <span class="sc">+</span> <span class="fu">scale_y_continuous</span>(<span class="at">labels =</span> scales<span class="sc">::</span>percent) <span class="sc">+</span> <span class="fu">ggtitle</span>(<span class="st">"Religious Affiliation in the 2001-2021 Censuses of England and Wales"</span>) <span class="sc">+</span> <span class="fu">xlab</span>(<span class="st">""</span>) <span class="sc">+</span> <span class="fu">ylab</span>(<span class="st">""</span>) <span class="sc">+</span> <span class="fu">theme</span>(<span class="at">axis.text.x =</span> <span class="fu">element_text</span>(<span class="at">angle =</span> <span class="dv">90</span>, <span class="at">vjust =</span> <span class="fl">0.5</span>, <span class="at">hjust=</span><span class="dv">1</span>))</span></code><button title="Copy to Clipboard" class="code-copy-button"><i class="bi"></i></button></pre></div>
<div class="sourceCode cell-code" id="cb27"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb27-1"><a href="#cb27-1" aria-hidden="true" tabindex="-1"></a><span class="fu">ggplot</span>(uk_census_merged_religion_ethnicity_nonwhite, <span class="fu">aes</span>(<span class="at">fill=</span>Year, <span class="at">x=</span>Religion, <span class="at">y=</span>Value)) <span class="sc">+</span> </span>
<span id="cb27-2"><a href="#cb27-2" aria-hidden="true" tabindex="-1"></a> <span class="fu">geom_bar</span>(<span class="at">position=</span><span class="st">"dodge"</span>, <span class="at">stat =</span><span class="st">"identity"</span>, <span class="at">colour =</span> <span class="st">"black"</span>) <span class="sc">+</span> </span>
<span id="cb27-3"><a href="#cb27-3" aria-hidden="true" tabindex="-1"></a> <span class="fu">facet_wrap</span>(<span class="sc">~</span>Ethnicity, <span class="at">ncol =</span> <span class="dv">2</span>) <span class="sc">+</span> </span>
<span id="cb27-4"><a href="#cb27-4" aria-hidden="true" tabindex="-1"></a> <span class="fu">scale_fill_brewer</span>(<span class="at">palette =</span> <span class="st">"Set1"</span>) <span class="sc">+</span> </span>
<span id="cb27-5"><a href="#cb27-5" aria-hidden="true" tabindex="-1"></a> <span class="fu">ggtitle</span>(<span class="st">"Religious Affiliation in the 2001-2021 Census of England and Wales"</span>) <span class="sc">+</span> </span>
<span id="cb27-6"><a href="#cb27-6" aria-hidden="true" tabindex="-1"></a> <span class="fu">xlab</span>(<span class="st">""</span>) <span class="sc">+</span> <span class="fu">ylab</span>(<span class="st">""</span>) <span class="sc">+</span> </span>
<span id="cb27-7"><a href="#cb27-7" aria-hidden="true" tabindex="-1"></a> <span class="fu">theme</span>(<span class="at">axis.text.x =</span> <span class="fu">element_text</span>(<span class="at">angle =</span> <span class="dv">90</span>, <span class="at">vjust =</span> <span class="fl">0.5</span>, <span class="at">hjust=</span><span class="dv">1</span>))</span></code><button title="Copy to Clipboard" class="code-copy-button"><i class="bi"></i></button></pre></div>
<div class="cell-output-display">
<div>
<figure class="figure">
@ -1001,13 +1030,47 @@ Statistics 101: Logarithmic Visualisation
</div>
</div>
</div>
<p>Now you can see why this shift is important - the visualisation tells a completely different story in some cases across the two different charts. In the first, working off raw numbers we see a net increase in Christianity across all categories. But if we take into account the fact that the overall share of population is growing for each of these groups, their actual composition is changing in a different direction. The proportion of each group is declining across the three census periods (albeit with an exception for the “Other” category from 2011 to 2021).</p>
<p>Were getting there, but as you can see there are a few formatting issues which remain. Our y-axis number labels are in scientific format which isnt easy to read. You can use the very powerful and flexible <code>scales()</code> library to bring in some more readable formatting of numbers in a variety of places in R including in ggplot visualizations.</p>
<div class="cell">
<div class="sourceCode cell-code" id="cb28"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb28-1"><a href="#cb28-1" aria-hidden="true" tabindex="-1"></a><span class="fu">library</span>(scales) <span class="sc">|&gt;</span> <span class="fu">suppressPackageStartupMessages</span>()</span>
<span id="cb28-2"><a href="#cb28-2" aria-hidden="true" tabindex="-1"></a><span class="fu">ggplot</span>(uk_census_merged_religion_ethnicity_nonwhite, <span class="fu">aes</span>(<span class="at">fill=</span>Year, <span class="at">x=</span>Religion, <span class="at">y=</span>Value)) <span class="sc">+</span> <span class="fu">geom_bar</span>(<span class="at">position=</span><span class="st">"dodge"</span>, <span class="at">stat =</span><span class="st">"identity"</span>, <span class="at">colour =</span> <span class="st">"black"</span>) <span class="sc">+</span> <span class="fu">facet_wrap</span>(<span class="sc">~</span>Ethnicity, <span class="at">ncol =</span> <span class="dv">2</span>) <span class="sc">+</span> <span class="fu">scale_fill_brewer</span>(<span class="at">palette =</span> <span class="st">"Set1"</span>) <span class="sc">+</span> <span class="fu">scale_y_continuous</span>(<span class="at">labels =</span> <span class="fu">unit_format</span>(<span class="at">unit =</span> <span class="st">"M"</span>, <span class="at">scale =</span> <span class="fl">1e-6</span>), <span class="at">breaks =</span> <span class="fu">breaks_extended</span>(<span class="dv">8</span>)) <span class="sc">+</span> <span class="fu">ggtitle</span>(<span class="st">"Religious Affiliation in the 2001-2021 Census of England and Wales"</span>) <span class="sc">+</span> <span class="fu">xlab</span>(<span class="st">""</span>) <span class="sc">+</span> <span class="fu">ylab</span>(<span class="st">""</span>) <span class="sc">+</span> <span class="fu">theme</span>(<span class="at">axis.text.x =</span> <span class="fu">element_text</span>(<span class="at">angle =</span> <span class="dv">90</span>, <span class="at">vjust =</span> <span class="fl">0.5</span>, <span class="at">hjust=</span><span class="dv">1</span>))</span></code><button title="Copy to Clipboard" class="code-copy-button"><i class="bi"></i></button></pre></div>
<div class="cell-output-display">
<div>
<figure class="figure">
<p><img src="chapter_1_files/figure-html/unnamed-chunk-31-1.png" class="img-fluid figure-img" width="672"></p>
</figure>
</div>
</div>
</div>
<p>This chart shows an increase in almost every category for each decade, though its a bit hard to read in some cases. However, if we attend to our hacker principles, theres another element here which can produce some misleading information. Consider for a moment how this information is based on the increase in <em>raw numbers</em>. Its possbile that the numbers for each religion category may be going up, but population levels are also rising, and its possible here that the percentage share for a particular category may have gone up a bit less than population increase, e.g.&nbsp;the share of the population for that category has actually gone <em>down</em>. This is easy to fix and provide some more accurate information by normalising those figures based on the share of overall population for each decade. Lets transform and visualise our data as percentages to see what kind of trends we can actually isolate:</p>
<div class="cell">
<div class="sourceCode cell-code" id="cb29"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb29-1"><a href="#cb29-1" aria-hidden="true" tabindex="-1"></a>uk_census_merged_religion_ethnicity <span class="ot">&lt;-</span> uk_census_merged_religion_ethnicity <span class="sc">%&gt;%</span></span>
<span id="cb29-2"><a href="#cb29-2" aria-hidden="true" tabindex="-1"></a> <span class="fu">group_by</span>(Ethnicity, Year) <span class="sc">%&gt;%</span></span>
<span id="cb29-3"><a href="#cb29-3" aria-hidden="true" tabindex="-1"></a> dplyr<span class="sc">::</span><span class="fu">mutate</span>(<span class="at">Percent =</span> Value<span class="sc">/</span><span class="fu">sum</span>(Value))</span>
<span id="cb29-4"><a href="#cb29-4" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb29-5"><a href="#cb29-5" aria-hidden="true" tabindex="-1"></a><span class="fu">ggplot</span>(uk_census_merged_religion_ethnicity, <span class="fu">aes</span>(<span class="at">fill=</span>Year, <span class="at">x=</span>Religion, <span class="at">y=</span>Percent)) <span class="sc">+</span> <span class="fu">geom_bar</span>(<span class="at">position=</span><span class="st">"dodge"</span>, <span class="at">stat =</span><span class="st">"identity"</span>, <span class="at">colour =</span> <span class="st">"black"</span>) <span class="sc">+</span> <span class="fu">facet_wrap</span>(<span class="sc">~</span>Ethnicity, <span class="at">scales=</span><span class="st">"free_x"</span>) <span class="sc">+</span> <span class="fu">scale_fill_brewer</span>(<span class="at">palette =</span> <span class="st">"Set1"</span>) <span class="sc">+</span> <span class="fu">scale_y_continuous</span>(<span class="at">labels =</span> scales<span class="sc">::</span>percent) <span class="sc">+</span> <span class="fu">ggtitle</span>(<span class="st">"Religious Affiliation in the 2001-2021 Censuses of England and Wales"</span>) <span class="sc">+</span> <span class="fu">xlab</span>(<span class="st">""</span>) <span class="sc">+</span> <span class="fu">ylab</span>(<span class="st">""</span>) <span class="sc">+</span> <span class="fu">theme</span>(<span class="at">axis.text.x =</span> <span class="fu">element_text</span>(<span class="at">angle =</span> <span class="dv">90</span>, <span class="at">vjust =</span> <span class="fl">0.5</span>, <span class="at">hjust=</span><span class="dv">1</span>))</span></code><button title="Copy to Clipboard" class="code-copy-button"><i class="bi"></i></button></pre></div>
<div class="cell-output-display">
<div>
<figure class="figure">
<p><img src="chapter_1_files/figure-html/unnamed-chunk-32-1.png" class="img-fluid figure-img" width="672"></p>
</figure>
</div>
</div>
</div>
<p>Now you can see why this shift is important - the visualisation tells a completely different story in some cases across the two different charts. In the first (working off raw numbers) we see a net increase in Christianity across all categories. But if we take into account the fact that the overall share of population is growing for each of these groups, their actual composition is changing in a different direction. The proportion of each group is declining across the three census periods (albeit with an exception for the “Other” category from 2011 to 2021).</p>
<p>To highlight a few of the technical features Ive added for this final plot, Ive used a specific feature within <code>facet_wrap</code> <code>scales = "free_x"</code> to let each of the individual facets adjust the total range on the x-axis. Since were looking at trends here and not absolute values, having correspondence across scales isnt important and this makes for something a bit more visually tidy. Ive also shifted the code for <code>scale_y_continuous</code> to render values as percentages (rather than millions).</p>
<p>In case you want to print this plot out and hang it on your wall, you can use the <code>ggsave</code> tool to render the chart as an image file which you can print or email to a friend (or professor!):</p>
<div class="cell">
<div class="sourceCode cell-code" id="cb28"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb28-1"><a href="#cb28-1" aria-hidden="true" tabindex="-1"></a>uk_census_merged_religion_ethnicity_plot <span class="ot">&lt;-</span> <span class="fu">ggplot</span>(uk_census_merged_religion_ethnicity, <span class="fu">aes</span>(<span class="at">fill=</span>Year, <span class="at">x=</span>Religion, <span class="at">y=</span>Percent)) <span class="sc">+</span> <span class="fu">geom_bar</span>(<span class="at">position=</span><span class="st">"dodge"</span>, <span class="at">stat =</span><span class="st">"identity"</span>, <span class="at">colour =</span> <span class="st">"black"</span>) <span class="sc">+</span> <span class="fu">facet_wrap</span>(<span class="sc">~</span>Ethnicity, <span class="at">scales=</span><span class="st">"free_x"</span>) <span class="sc">+</span> <span class="fu">scale_fill_brewer</span>(<span class="at">palette =</span> <span class="st">"Set1"</span>) <span class="sc">+</span> <span class="fu">scale_y_continuous</span>(<span class="at">labels =</span> scales<span class="sc">::</span>percent) <span class="sc">+</span> <span class="fu">ggtitle</span>(<span class="st">"Religious Affiliation in the 2001-2021 Censuses of England and Wales"</span>) <span class="sc">+</span> <span class="fu">xlab</span>(<span class="st">""</span>) <span class="sc">+</span> <span class="fu">ylab</span>(<span class="st">""</span>) <span class="sc">+</span> <span class="fu">theme</span>(<span class="at">axis.text.x =</span> <span class="fu">element_text</span>(<span class="at">angle =</span> <span class="dv">90</span>, <span class="at">vjust =</span> <span class="fl">0.5</span>, <span class="at">hjust=</span><span class="dv">1</span>))</span>
<span id="cb28-2"><a href="#cb28-2" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb28-3"><a href="#cb28-3" aria-hidden="true" tabindex="-1"></a><span class="fu">ggsave</span>(<span class="st">"figures/chart.png"</span>, <span class="at">plot=</span>uk_census_merged_religion_ethnicity_plot, <span class="at">width =</span> <span class="dv">8</span>, <span class="at">height =</span> <span class="dv">10</span>, <span class="at">units=</span><span class="fu">c</span>(<span class="st">"in"</span>))</span></code><button title="Copy to Clipboard" class="code-copy-button"><i class="bi"></i></button></pre></div>
<div class="sourceCode cell-code" id="cb30"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb30-1"><a href="#cb30-1" aria-hidden="true" tabindex="-1"></a>uk_census_merged_religion_ethnicity_plot <span class="ot">&lt;-</span> <span class="fu">ggplot</span>(uk_census_merged_religion_ethnicity, <span class="fu">aes</span>(<span class="at">fill=</span>Year, <span class="at">x=</span>Religion, <span class="at">y=</span>Percent)) <span class="sc">+</span> </span>
<span id="cb30-2"><a href="#cb30-2" aria-hidden="true" tabindex="-1"></a> <span class="fu">geom_bar</span>(<span class="at">position=</span><span class="st">"dodge"</span>, <span class="at">stat =</span><span class="st">"identity"</span>, <span class="at">colour =</span> <span class="st">"black"</span>) <span class="sc">+</span> </span>
<span id="cb30-3"><a href="#cb30-3" aria-hidden="true" tabindex="-1"></a> <span class="fu">facet_wrap</span>(<span class="sc">~</span>Ethnicity, <span class="at">scales=</span><span class="st">"free_x"</span>) <span class="sc">+</span> </span>
<span id="cb30-4"><a href="#cb30-4" aria-hidden="true" tabindex="-1"></a> <span class="fu">scale_fill_brewer</span>(<span class="at">palette =</span> <span class="st">"Set1"</span>) <span class="sc">+</span> </span>
<span id="cb30-5"><a href="#cb30-5" aria-hidden="true" tabindex="-1"></a> <span class="fu">scale_y_continuous</span>(<span class="at">labels =</span> scales<span class="sc">::</span>percent) <span class="sc">+</span> </span>
<span id="cb30-6"><a href="#cb30-6" aria-hidden="true" tabindex="-1"></a> <span class="fu">ggtitle</span>(<span class="st">"Religious Affiliation in the 2001-2021 Censuses of England and Wales"</span>) <span class="sc">+</span> </span>
<span id="cb30-7"><a href="#cb30-7" aria-hidden="true" tabindex="-1"></a> <span class="fu">xlab</span>(<span class="st">""</span>) <span class="sc">+</span> <span class="fu">ylab</span>(<span class="st">""</span>) <span class="sc">+</span> </span>
<span id="cb30-8"><a href="#cb30-8" aria-hidden="true" tabindex="-1"></a> <span class="fu">theme</span>(<span class="at">axis.text.x =</span> <span class="fu">element_text</span>(<span class="at">angle =</span> <span class="dv">90</span>, <span class="at">vjust =</span> <span class="fl">0.5</span>, <span class="at">hjust=</span><span class="dv">1</span>))</span>
<span id="cb30-9"><a href="#cb30-9" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb30-10"><a href="#cb30-10" aria-hidden="true" tabindex="-1"></a><span class="fu">ggsave</span>(<span class="st">"figures/chart.png"</span>, <span class="at">plot=</span>uk_census_merged_religion_ethnicity_plot, <span class="at">width =</span> <span class="dv">8</span>, <span class="at">height =</span> <span class="dv">10</span>, <span class="at">units=</span><span class="fu">c</span>(<span class="st">"in"</span>))</span></code><button title="Copy to Clipboard" class="code-copy-button"><i class="bi"></i></button></pre></div>
</div>
<p>Thats a pretty good days work. Weve covered bifactorial analysis of the census data, compared this across years, and checked in each case to be sure that were representing the data accurately in the various visual elements of our charts. For the next chapter, were going to explore a wider range of ways to measure and represent religion.</p>
<p>In the meantime, if you want to download the R code without all the commentary here so you can try running it in a browser, you can download that from the cookbook repository.</p>
@ -1098,6 +1161,24 @@ window.document.addEventListener("DOMContentLoaded", function (event) {
// clear code selection
e.clearSelection();
});
var localhostRegex = new RegExp(/^(?:http|https):\/\/localhost\:?[0-9]*\//);
var mailtoRegex = new RegExp(/^mailto:/);
var filterRegex = new RegExp('/' + window.location.host + '/');
var isInternal = (href) => {
return filterRegex.test(href) || localhostRegex.test(href) || mailtoRegex.test(href);
}
// Inspect non-navigation links and adorn them if external
var links = window.document.querySelectorAll('a[href]:not(.nav-link):not(.navbar-brand):not(.toc-action):not(.sidebar-link):not(.sidebar-item-toggle):not(.pagination-link):not(.no-external):not([aria-hidden]):not(.dropdown-item):not(.quarto-navigation-tool)');
for (var i=0; i<links.length; i++) {
const link = links[i];
if (!isInternal(link.href)) {
// undo the damage that might have been done by quarto-nav.js in the case of
// links that we want to consider external
if (link.dataset.originalHref !== undefined) {
link.href = link.dataset.originalHref;
}
}
}
function tippyHover(el, contentFn, onTriggerFn, onUntriggerFn) {
const config = {
allowHTML: true,
@ -1132,7 +1213,11 @@ window.document.addEventListener("DOMContentLoaded", function (event) {
try { href = new URL(href).hash; } catch {}
const id = href.replace(/^#\/?/, "");
const note = window.document.getElementById(id);
if (note) {
return note.innerHTML;
} else {
return "";
}
});
}
const xrefs = window.document.querySelectorAll('a.quarto-xref');
@ -1410,13 +1495,13 @@ window.document.addEventListener("DOMContentLoaded", function (event) {
</script>
<nav class="page-navigation">
<div class="nav-page nav-page-previous">
<a href="./index.html" class="pagination-link aria-label=" introduction:="" hacking="" religion"="">
<a href="./index.html" class="pagination-link" aria-label="Introduction: Hacking Religion">
<i class="bi bi-arrow-left-short"></i> <span class="nav-page-text">Introduction: Hacking Religion</span>
</a>
</div>
<div class="nav-page nav-page-next">
<a href="./chapter_2.html" class="pagination-link" aria-label="<span class='chapter-number'>2</span>&nbsp; <span class='chapter-title'>Getting into the nitty-gritty details</span>">
<span class="nav-page-text"><span class="chapter-number">2</span>&nbsp; <span class="chapter-title">Getting into the nitty-gritty details</span></span> <i class="bi bi-arrow-right-short"></i>
<a href="./chapter_2.html" class="pagination-link" aria-label="Different ways to measure religion using data science">
<span class="nav-page-text"><span class="chapter-number">2</span>&nbsp; <span class="chapter-title">Different ways to measure religion using data science</span></span> <i class="bi bi-arrow-right-short"></i>
</a>
</div>
</nav>

Binary file not shown.

Before

Width:  |  Height:  |  Size: 32 KiB

After

Width:  |  Height:  |  Size: 31 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 52 KiB

After

Width:  |  Height:  |  Size: 50 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 52 KiB

After

Width:  |  Height:  |  Size: 50 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 58 KiB

After

Width:  |  Height:  |  Size: 58 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 60 KiB

After

Width:  |  Height:  |  Size: 60 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 62 KiB

After

Width:  |  Height:  |  Size: 66 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 68 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 71 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 63 KiB

After

Width:  |  Height:  |  Size: 71 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 59 KiB

After

Width:  |  Height:  |  Size: 63 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 65 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 59 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 71 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 81 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 100 KiB

After

Width:  |  Height:  |  Size: 71 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 81 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 100 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 23 KiB

After

Width:  |  Height:  |  Size: 23 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 26 KiB

After

Width:  |  Height:  |  Size: 25 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 25 KiB

After

Width:  |  Height:  |  Size: 24 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 29 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 42 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 42 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 88 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 90 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 99 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 102 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 100 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 92 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 94 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 47 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 100 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 112 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 127 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 14 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 17 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 19 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 19 KiB

View file

@ -2,7 +2,7 @@
<html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en"><head>
<meta charset="utf-8">
<meta name="generator" content="quarto-1.4.549">
<meta name="generator" content="quarto-1.4.551">
<meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=yes">
@ -122,7 +122,7 @@ ul.task-list li input[type="checkbox"] {
<li class="sidebar-item">
<div class="sidebar-item-container">
<a href="./chapter_2.html" class="sidebar-item-text sidebar-link">
<span class="menu-text"><span class="chapter-number">2</span>&nbsp; <span class="chapter-title">Getting into the nitty-gritty details</span></span></a>
<span class="menu-text"><span class="chapter-number">2</span>&nbsp; <span class="chapter-title">Different ways to measure religion using data science</span></span></a>
</div>
</li>
<li class="sidebar-item">
@ -213,35 +213,35 @@ ul.task-list li input[type="checkbox"] {
<h1 class="unnumbered">Introduction: Hacking Religion</h1>
<section id="why-this-book" class="level2">
<h2 class="anchored" data-anchor-id="why-this-book">Why this book?</h2>
<p>Data science is quickly consolidating as a new field, with new tools and user communities emerging seemingly every week. At the same time the field of academic research has opened up into new interdisciplinary vistas, with experts crossing over into new fields, transgressing disciplinary boundaries and deploying tools in new and unexpected ways to develop knowledge. There are many gaps yet to be filled, but one which I found to be particularly glaring is the lack of applied data science documentation around the subject of religion. On one hand, scholars who are working with cutting edge theory seldom pick up these emerging tools of data science. On the other hand, data scientists rarely go beyond dabbling in religious themes, leaving quite a lot of really interesting theoretical research untouched. This book aims to bring these two things together: introducing the tools of data science in an applied way, whilst introducing some of the complexities and cutting edge theories which help us to conceptualise and frame our understanding of this knowledge regarding religion in the world around us.</p>
<p>Data science is quickly consolidating as a new field, with new tools and user communities emerging every week. At the same time academic research has opened up into new interdisciplinary vistas, with experts crossing over into new fields, transgressing disciplinary boundaries and deploying tools in new and unexpected ways to develop knowledge. There are many gaps yet to be filled, but one which I found to be particularly glaring is the lack of applied data science documentation around the subject of religion. On one hand, scholars who are working with cutting edge theory seldom pick up these emerging tools of data science. On the other hand, data scientists rarely go beyond dabbling in religious themes, leaving quite a lot of really interesting theoretical research untouched. This book aims to bring these two things together: introducing the tools of data science in an applied way, whilst introducing some of the complexities and cutting edge theories which help us to conceptualise and frame our understanding of this knowledge regarding religion in the world around us.</p>
</section>
<section id="the-hacker-way" class="level2">
<h2 class="anchored" data-anchor-id="the-hacker-way">The hacker way</h2>
<p>Its worth emphasising at the outset that this isnt meant to be a generic data science book. My own training as a researcher lies in the field of religious ethics, and my engagement with digital technology has, from the very start, been a context for exploring matters of personal values and social action. A fair bit of ink has been spilled in books, magazines, blogs and zines unpacking what exactly it means to be a “hacker”. Pressing beyond some of the more superficial cultural stereotypes, I want to explain a bit here about how hacking can be a much more substantial vision for ethical engagement with technology and social transformation.</p>
<p>Back in the 1980s Steven Levy tried to capture some of this in his book “Hackers: Heroes of the Computer Revolution”. As Levy put it, the “hacker ethic” included: (1) sharing, (2) openness, (3) decentralisation, (4) free access to computers and (5) world improvement. The key point here is that hacking isnt just about writing and breaking code, or testing and finding weaknesses in computer systems and networks. There is often a more substantial underpinning ethical code which dovetails with on-the-surface matters of curiosity and craft.</p>
<p>This emphasis on ethics is especially important when were doing data science because this kind of research work will put you in positions of influence and bestow upon you a certain amount of social influence. You might think this seems a bit overstated, but it never ceases to amaze me how much bringing a bar chart which succinctly shows a social trend can sway a conversation or decision making process. There is something unusually persuasive that comes with the combination of aesthetics, data and storytelling. Ive met many people who have come to data science out of a desire to bring about social transformation in some sphere of life. People want to use technology and communication to make the world better. However, its possible that this can quickly get out of hand. With this in mind, Ive found that it can be important to have a clear sense of what sorts of convictions guide your work in this field: a “hacker code” of sorts. Here are the principles that I have settled on in my own practice of hacking religion:</p>
<p>This emphasis on ethics is especially important when were doing data science because this kind of research work will put you in positions of influence. You might think this seems a bit overstated, but it never ceases to amaze me how much bringing a bar chart which succinctly shows a social trend can sway a conversation or decision making process. There is something unusually persuasive that comes with the combination of aesthetics, data and storytelling. Ive met many people who have come to data science out of a desire to bring about social transformation in some sphere of life. People want to use technology and communication to make the world better. However, its possible that this can quickly get out of hand. With this in mind, Ive found that it can be important to have a clear sense of the convictions that guide your work in this field: a “hacker code” of sorts. Here are the principles that I have settled on in my own practice of hacking religion:</p>
<ol type="1">
<li>Tell the truth: be candid about your limits, use visualisation responsibly</li>
<li>Work transparently: open data, open code</li>
<li>Work in community: draw others in by producing reproducible research</li>
<li>Work with reality and learn by doing</li>
<li><em>Tell the truth</em>: be candid about your limits, use visualisation responsibly</li>
<li><em>Work transparently</em>: open data, open code</li>
<li><em>Work in community</em>: draw others in by producing reproducible research</li>
<li><em>Work with reality</em> and learn by doing</li>
</ol>
<p>It never ceases to amaze me how often people think that, when theyre working for something they think is important it is acceptable to conceal bad news or amplify good or compelling information beyond its real scope. There are always consequences, eventually. When people realise youve been misleading or manipulating them your platform and credibility will evaporate. Good work mixed with bad will all get tossed out. And sometimes, our convictions can lead us beyond our true apprehension of a situation.</p>
<p>It never ceases to amaze me how often people think that, when theyre working for something they think is important it is acceptable to conceal bad news or amplify good or compelling information beyond its real scope. There are always consequences, eventually. When people realise youve been misleading or manipulating them your platform and credibility will evaporate. Good work mixed with bad will all get tossed out. And sometimes, our convictions can lead us beyond an accurate and true apprehension of the situation we are focussed on in research.</p>
<p>Presenting through “facts” an argument can become unnaturally compelling. Wrapping those facts up in something that uses colour, line and shape in a way that is aesthetically pleasing, even beautiful, enhances this allure even further. As you craft your own set of hacker principles, its vitally important that you always strive to tell the truth. This includes a willingness to acknowledge the limits of your information, and to share the whole set of information. The easiest way to do this is to work with visualation in a responsible way (Ill get into this a bit more in Chapter 1) and to open up your data and code to scrutiny. By allowing others to try, criticise, edit, and reappropriate your code and data in their own ways, you contribute to knowledge and help to build up a community of accountability. The upside of this is that its also a lot more fun and interesting to work alongside others.</p>
<p>Far too often, scholarly research (and theology) has been criticised for being disconnected from reality, making abstract pie-in-the-sky claims about how life should be lived. When exposed to the uncomfortable pressures of reality, these claims can crumble, or even turn sinister. One of the upsides of working with empirical research is that you have a chance to engage with the real world. For this reason, I love to do ethics in a way that arises - bottom-up - from real world experiences and relationships. Theres also the potential (at least in the best case scenario) that when we make choices based on reliable information drawn from everyday reality our policy and culture can be more resilient and accountable. This also works well with the hacker ethos of “learning by doing” and its this approach that guides my approach in this book. This isnt just a book about data analysis, Im proposing an approach which might be thought of as research-as-code, where you write out instructions to execute the various steps of work. The upside of this is that other researchers can learn from your work, correct and build on it as part of an intellectual commons. It takes a bit more time to learn and set things up, but the upside is that youll gain access to a set of tools and a research philosophy which is much more powerful.</p>
<p>Ill return to these principles periodically as we work through the coding and data in this book.</p>
</section>
<section id="learning-to-code-my-way" class="level2">
<h2 class="anchored" data-anchor-id="learning-to-code-my-way">Learning to code: my way</h2>
<p>Alongside these guiding principles, its also worth saying a bit about how I like to design teaching and learning. Some readers may notice that this guide is a little different from other textbooks targetting learning to code. I remember when I was first starting out, I went through a fair few guides, and they all tended to spend about 200 pages on various theoretical bits, how you form an integer, or data structures, subroutines, the logical structure of algorithms etc. etc. It was usually weeks of reading before I got to actually <em>do</em> anything. I know some people may prefer this approach, but I prefer a problem-focussed approach to learning. Give me something that is broken, or a problem to solve, which engages the things I want to figure out and the motivation for learning just comes much more naturally. And we know from research in cognitive science that these kinds of problem-focussed approaches can tend to faciliate faster learning and better retention, so its not just my personal preference, but also justified! It will be helpful for you to be aware of this approach when you get into the book as it explains some of the editorial choices Ive made and the way Ive structured things.</p>
<p>Alongside these guiding principles, its also worth saying a bit about how I like to design teaching and learning. I remember when I was first starting out, and gathered coding manuals to read and learn from. They all tended to spend the first several hundred pages on theory, how you form an integer, data structures, subroutines, the logical structure of algorithms etc. etc. It was usually weeks of reading before I got to actually <em>do</em> anything. I know some people may prefer this approach, but I prefer a problem-focussed approach to learning. Give me something that is broken, or a problem to solve, which engages the things I want to figure out and the motivation for learning just comes much more naturally. And we know from research in cognitive science that these kinds of problem-focussed approaches can tend to faciliate faster learning and better retention. It will be helpful for you to be aware of this approach when you get into the book as it explains some of the editorial choices Ive made and the way Ive structured things.</p>
<p>Each chapter focusses on a series of <em>problems</em> which are particularly salient for the use of data science to conduct research into religion. These problems will be my focal point, guiding choices of specific aspects of programming to introduce to you as we work our way around that dataset and some of the crucial questions that arise in terms of how we handle it. If you find this approach unsatisfying, luckily there are a number of really terrific guides which lay things out slowly and methodically and I will explicitly signpost some of these along the way so that you can do a “deep dive” when you feel like it. You can also find a list of resources in Appendix B to this book. Otherwise, Ill take an accelerated approach to this introduction to data science in R. I expect that you will identify adjacent resources and perhaps even come up with your own creative approaches along the way, which incidentally is how real data science tends to work in practice.</p>
<p>There are a range of terrific textbooks out there which cover all these elements in greater depth and more slowly. In particular, Id recommend that many readers will want to check out Hadley Wickhams “<a href="https://r4ds.hadley.nz/">R For Data Science</a>” book. Ill include marginal notes in this guide pointing to sections of that book, and a few others which unpack the basic mechanics of R in more detail.</p>
<p>There are a range of terrific textbooks which cover all these elements in greater depth and more slowly. In particular, Id recommend that many readers will want to check out Hadley Wickhams “<a href="https://r4ds.hadley.nz/">R For Data Science</a>” book. Ill include marginal notes in this guide pointing to sections of that book, and a few others which unpack the basic mechanics of R in more detail.</p>
</section>
<section id="getting-set-up" class="level2">
<h2 class="anchored" data-anchor-id="getting-set-up">Getting set up</h2>
<p>Every single tool, programming language and data set we refer to in this book is free and open source. These tools have been produced by professionals and volunteers who are passionate about data science and research and want to share it with the world, and in order to do this (and following the “hacker way”) theyve made these tools freely available. This also means that you arent restricted to a specific proprietary, expensive, or unavailable piece of software to do this work. Ill make a few opinionated recommendations here based on my own preferences and experience, but its really up to your own style and approach. In fact, given that this is an open source textbook, you can even propose additions to this chapter explaining other tools youve found that you want to share with others.</p>
<p>There are, right now, primarily two languages that statisticians and data scientists use for this kind of programmatic data science: python and R. Each language has its merits and I wont rehash the debates between various factions. For this book, well be using the R language. This is, in part, because the R user community and libraries tend to scale a bit better for the work that Im commending in this book. However, its entirely possible that one could use python for all these exercises, and perhaps in the future well have volume two of this book outlining python approaches to the same operations.</p>
<p>Bearing this in mind, the first step youll need to take is to download and install R. You can find instructions and install packages for a wide range of hardware on a key resource online for R programmers: the The Comprehensive R Archive Network (or “CRAN”): https://cran.rstudio.com. Once youve installed R, youve got some choices to make about the kind of programming environment youd like to use. You can just use a plain text editor like <code>textedit</code> to write your code and then execute your programs using the R software youve just installed. However, most users, myself included, tend to use an integrated development environment (or “IDE”). This is usually another software package with a guided user interface and some visual elements that make it faster to write and test your code. Some IDE packages, will have built-in reference tools so you can look up options for libraries you use in your code, they will allow you to visualise the results of your code execution, and perhaps most important of all, will enable you to execute your programs line by line so you can spot errors more quickly (we call this “debugging”). The two most popular IDE platforms for R coding at the time of writing this textbook are RStudio and Visual Studio. You should download and try out both and stick with your favourite, as the differences are largely aesthetic. I use a combination of RStudio and an enhanced plain text editor Sublime Text for my coding.</p>
<p>Every single tool, programming language and data set we refer to in this book is free and open source. These tools have been produced by professionals and volunteers who are passionate about data science and research and want to share it with the world, and in order to do this (and following the “hacker way”) theyve made these tools freely available. This also means that you arent restricted to a specific proprietary, expensive, or unavailable piece of software to do this work. Ill make a few opinionated recommendations here based on my own preferences and experience, but its really up to your own style and approach. In fact, given that this is an open source textbook, you can even propose additions to this chapter online sharing other tools youve found that you want to share with others.</p>
<p>There are, right now, primarily two languages that statisticians and data scientists use for this kind of programmatic data science: python and R. Each language has its merits and I wont rehash the debates between various factions. For this book, well be using the R language. This is, in part, because Ive found that the R user community and libraries tend to scale a bit better for the work that Im commending in this book. However, its entirely possible that one could use python for all these exercises, and Ill release a future version of this volume outlining python approaches to hacking religion.</p>
<p>Bearing this in mind, the first step youll need to take is to download and install R. You can find instructions and install packages for a wide range of hardware on a key resource online for R programmers: The Comprehensive R Archive Network (or “CRAN”): https://cran.rstudio.com. Once youve installed R, youve got some choices to make about the kind of programming environment youd like to use. You can just use a plain text editor like <code>textedit</code> to write your code and then execute your programs using the R software youve just installed. However, most users, myself included, tend to use an integrated development environment (or “IDE”). This is usually another software package with a guided user interface and some visual elements that make it faster to write and test your code. Some IDE packages will have built-in reference tools so you can look up options for libraries you use in your code. They will allow you to visualise the results of your code execution and perhaps most important of all, will enable you to execute your programs line by line so you can spot errors more quickly (we call this “debugging”). The two most popular IDE platforms for R coding at the time of writing this textbook are RStudio and Visual Studio. You should download and try out both and stick with your favourite, as the differences are largely aesthetic. I use a combination of RStudio and an enhanced plain text editor Sublime Text for my coding.</p>
<p>Once you have R and your pick of an IDE, you are ready to go! Proceed to the next chapter and well dive right in and get started!</p>
@ -328,6 +328,24 @@ window.document.addEventListener("DOMContentLoaded", function (event) {
// clear code selection
e.clearSelection();
});
var localhostRegex = new RegExp(/^(?:http|https):\/\/localhost\:?[0-9]*\//);
var mailtoRegex = new RegExp(/^mailto:/);
var filterRegex = new RegExp('/' + window.location.host + '/');
var isInternal = (href) => {
return filterRegex.test(href) || localhostRegex.test(href) || mailtoRegex.test(href);
}
// Inspect non-navigation links and adorn them if external
var links = window.document.querySelectorAll('a[href]:not(.nav-link):not(.navbar-brand):not(.toc-action):not(.sidebar-link):not(.sidebar-item-toggle):not(.pagination-link):not(.no-external):not([aria-hidden]):not(.dropdown-item):not(.quarto-navigation-tool)');
for (var i=0; i<links.length; i++) {
const link = links[i];
if (!isInternal(link.href)) {
// undo the damage that might have been done by quarto-nav.js in the case of
// links that we want to consider external
if (link.dataset.originalHref !== undefined) {
link.href = link.dataset.originalHref;
}
}
}
function tippyHover(el, contentFn, onTriggerFn, onUntriggerFn) {
const config = {
allowHTML: true,
@ -362,7 +380,11 @@ window.document.addEventListener("DOMContentLoaded", function (event) {
try { href = new URL(href).hash; } catch {}
const id = href.replace(/^#\/?/, "");
const note = window.document.getElementById(id);
if (note) {
return note.innerHTML;
} else {
return "";
}
});
}
const xrefs = window.document.querySelectorAll('a.quarto-xref');
@ -642,7 +664,7 @@ window.document.addEventListener("DOMContentLoaded", function (event) {
<div class="nav-page nav-page-previous">
</div>
<div class="nav-page nav-page-next">
<a href="./chapter_1.html" class="pagination-link" aria-label="<span class='chapter-number'>1</span>&nbsp; <span class='chapter-title'>Set up local workspace:</span>">
<a href="./chapter_1.html" class="pagination-link" aria-label="Set up local workspace:">
<span class="nav-page-text"><span class="chapter-number">1</span>&nbsp; <span class="chapter-title">Set up local workspace:</span></span> <i class="bi bi-arrow-right-short"></i>
</a>
</div>

File diff suppressed because one or more lines are too long

512
hacking_religion/.Rhistory Normal file
View file

@ -0,0 +1,512 @@
) %>% factor(levels = c("low", "medium", "high"))
)
## we need to convert data to factors on named response data
climate_experience_data$Q67 <- climate_experience_data$Q67 %>%
mutate(
income_bin = case_when(
as.data.frame(climate_experience_data$Q67) > 6 ~ "high",
as.data.frame(climate_experience_data$Q67) < 3 ~ "low",
TRUE ~ "medium"
) %>% factor(levels = c("low", "medium", "high"))
)
## Q8 subsetting based on confidence on views
climate_experience_data <- climate_experience_data %>%
mutate(
Q8_bin = case_when(
Q8_1 > mean(Q8_1) + sd(Q8_1) ~ "high",
Q8_1 < mean(Q8_1) - sd(Q8_1) ~ "low",
TRUE ~ "medium"
) %>% factor(levels = c("low", "medium", "high"))
)
# Q53 subsetting based on Political LR orientation:
# Generate low/med/high bins based on Mean and SD
climate_experience_data <- climate_experience_data %>%
mutate(
Q53_bin = case_when(
Q53_1 > mean(Q53_1) + sd(Q53_1) ~ "high",
Q53_1 < mean(Q53_1) - sd(Q53_1) ~ "low",
TRUE ~ "medium"
) %>% factor(levels = c("low", "medium", "high"))
)
## Q57 subsetting based on Religiosity
climate_experience_data <- climate_experience_data %>%
mutate(
Q57_bin = case_when(
Q57_1 > mean(Q57_1) + sd(Q57_1) ~ "high",
Q57_1 < mean(Q57_1) - sd(Q57_1) ~ "low",
TRUE ~ "medium"
) %>% factor(levels = c("low", "medium", "high"))
)
## Subsetting based on Spirituality
# Calculate overall mean nature-relatedness score based on six questions:
climate_experience_data$Q51_score <- rowMeans(select(climate_experience_data, Q51_remote_vacation:Q51_heritage))
# Create low/med/high bins based on Mean and +1/-1 Standard Deviation
climate_experience_data <- climate_experience_data %>%
mutate(
Q51_bin = case_when(
Q51_score > mean(Q51_score) + sd(Q51_score) ~ "high",
Q51_score < mean(Q51_score) - sd(Q51_score) ~ "low",
TRUE ~ "medium"
) %>% factor(levels = c("low", "medium", "high"))
)
# Calculate overall mean spirituality score based on six questions:
climate_experience_data$Q52_score <- rowMeans(select(climate_experience_data, Q52a_1:Q52f_1))
# Create low/med/high bins based on Mean and +1/-1 Standard Deviation
climate_experience_data <- climate_experience_data %>%
mutate(
Q52_bin = case_when(
Q52_score > mean(Q52_score) + sd(Q52_score) ~ "high",
Q52_score < mean(Q52_score) - sd(Q52_score) ~ "low",
TRUE ~ "medium"
) %>% factor(levels = c("low", "medium", "high"))
)
# Generate new column with simplified postcode area data (only initial alpha characters)
# Note: this data has been embargoed for the sake of respondent confidentiality and will not likely be included in any future releases
climate_experience_data$postcode_area <- str_to_upper(str_extract(climate_experience_data_named$Q68, "^([A-Z,a-z]){1,}"))
# Generate new column with simplified postcode area data (only initial alpha characters)
# Note: this data has been embargoed for the sake of respondent confidentiality and will not likely be included in any future releases
climate_experience_data$postcode_area <- str_to_upper(str_extract(climate_experience_data$Q68, "^([A-Z,a-z]){1,}"))
# Add identifier flagging London residents
climate_experience_data <- climate_experience_data %>%
rowwise() %>%
mutate(
isLondon = case_when(
postcode_area == "E" ~ "1",
postcode_area == "EC" ~ "1",
postcode_area == "N" ~ "1",
postcode_area == "NW" ~ "1",
postcode_area == "SE" ~ "1",
postcode_area == "SW" ~ "1",
postcode_area == "W" ~ "1",
postcode_area == "WC" ~ "1",
TRUE ~ "0"
)
)
#| include: true
#| label: fig-polar
setwd("/Users/kidwellj/gits/hacking_religion_textbook/hacking_religion")
library(here) |> suppressPackageStartupMessages()
library(tidyverse) |> suppressPackageStartupMessages()
here::i_am("chapter_1.qmd")
# Set up local workspace:
if (dir.exists("data") == FALSE) {
dir.create("data")
}
if (dir.exists("figures") == FALSE) {
dir.create("figures")
}
if (dir.exists("derivedData") == FALSE) {
dir.create("derivedData")
}
uk_census_2021_religion <- read.csv(here("example_data", "census2021-ts030-rgn.csv"))
head(uk_census_2021_religion)
knitr::kable(head(uk_census_2021_religion))
knitr::kable(head(uk_census_2021_religion))
uk_census_2021_religion_wmids <- uk_census_2021_religion_wmids %>% select(no_religion:no_response)
uk_census_2021_religion_wmids <- uk_census_2021_religion %>% filter(geography=="West Midlands")
uk_census_2021_religion_wmids <- uk_census_2021_religion_wmids %>% select(no_religion:no_response)
uk_census_2021_religion_wmids <- gather(uk_census_2021_religion_wmids)
df <- uk_census_2021_religion_wmids[order(uk_census_2021_religion_wmids$value,decreasing = TRUE),]
barplot(height=df$value, names=df$key)
ggplot(uk_census_2021_religion_wmids, aes(x = key, y = value)) + geom_bar(stat = "identity") # <1>
ggplot(uk_census_2021_religion_wmids, aes(x= reorder(key,-value),value)) + geom_bar(stat ="identity") # <2>
uk_census_2021_religion_totals <- uk_census_2021_religion %>% select(no_religion:no_response) # <1>
uk_census_2021_religion_totals <- uk_census_2021_religion_totals %>%
summarise(across(everything(), ~ sum(., na.rm = TRUE))) # <2>
uk_census_2021_religion_totals <- gather(uk_census_2021_religion_totals) # <3>
ggplot(uk_census_2021_religion_totals, aes(x= reorder(key,-value),value)) + geom_bar(stat ="identity") # <4>
uk_census_2021_religion_merged <- rbind(uk_census_2021_religion_totals, uk_census_2021_religion_wmids)
uk_census_2021_religion_totals$dataset <- c("totals")
uk_census_2021_religion_wmids$dataset <- c("wmids")
uk_census_2021_religion_merged <- rbind(uk_census_2021_religion_totals, uk_census_2021_religion_wmids)
ggplot(uk_census_2021_religion_merged, aes(fill=dataset, x= reorder(key,-value), value)) + geom_bar(position="dodge", stat ="identity")
uk_census_2021_religion_totals <- uk_census_2021_religion_totals %>%
dplyr::mutate(perc = scales::percent(value / sum(value), accuracy = 0.1, trim = FALSE)) # <3>
uk_census_2021_religion_wmids <- uk_census_2021_religion_wmids %>%
dplyr::mutate(perc = scales::percent(value / sum(value), accuracy = 0.1, trim = FALSE)) # <3>
uk_census_2021_religion_merged <- rbind(uk_census_2021_religion_totals, uk_census_2021_religion_wmids)
ggplot(uk_census_2021_religion_merged, aes(fill=dataset, x=key, y=perc)) + geom_bar(position="dodge", stat ="identity")
ggplot(uk_census_2021_religion_merged, aes(fill=dataset, x= reorder(key,-value), value)) + geom_bar(position="dodge", stat ="identity")
uk_census_2021_religion_totals <- uk_census_2021_religion_totals %>%
dplyr::mutate(perc = scales::percent(value / sum(value), accuracy = 0.1, trim = FALSE)) # <3>
uk_census_2021_religion_wmids <- uk_census_2021_religion_wmids %>%
dplyr::mutate(perc = scales::percent(value / sum(value), accuracy = 0.1, trim = FALSE)) # <3>
uk_census_2021_religion_merged <- rbind(uk_census_2021_religion_totals, uk_census_2021_religion_wmids)
ggplot(uk_census_2021_religion_merged, aes(fill=dataset, x=key, y=perc)) + geom_bar(position="dodge", stat ="identity")
ggplot(uk_census_2021_religion_merged, aes(fill=dataset, x=key, y=perc)) + geom_bar(position="dodge", stat ="identity") + scale_fill_brewer(palette = "Set1")
uk_census_2021_religion_merged$dataset <- factor(uk_census_2021_religion_merged$dataset, levels = c('wmids', 'totals'))
ggplot(uk_census_2021_religion_merged, aes(fill=fct_reorder(dataset, value), x=reorder(key,-value),value, y=perc)) + geom_bar(position="dodge", stat ="identity", colour = "black") + scale_fill_brewer(palette = "Set1")
ggplot(uk_census_2021_religion_merged, aes(fill=fct_reorder(dataset, value), x=reorder(key,-value),value, y=perc)) + geom_bar(position="dodge", stat ="identity", colour = "black") + scale_fill_brewer(palette = "Set1") + theme(axis.text.x = element_text(angle = 90, vjust = 0.5, hjust=1))
ggplot(uk_census_2021_religion_merged, aes(fill=fct_reorder(dataset, value), x=reorder(key,-value),value, y=perc)) + geom_bar(position="dodge", stat ="identity", colour = "black") + scale_fill_brewer(palette = "Set1") + ggtitle("Religious Affiliation in the UK: 2021") + xlab("") + ylab("")
ggplot(uk_census_2021_religion_merged, aes(fill=fct_reorder(dataset, value), x=reorder(key,-value),value, y=perc))
ggplot(uk_census_2021_religion_merged, aes(fill=fct_reorder(dataset, value), x=reorder(key,-value),value, y=perc)) + geom_bar(position="dodge", stat ="identity", colour = "black") + scale_fill_brewer(palette = "Set1") + ggtitle("Religious Affiliation in the UK: 2021") + xlab("") + ylab("")
ggplot(uk_census_2021_religion_merged, aes(fill=fct_reorder(dataset, value), x=reorder(key,-value),value, y=perc)) + geom_bar(position="dodge", stat ="identity", colour = "black") + scale_fill_brewer(palette = "Set1") + ggtitle("Religious Affiliation in the UK: 2021") + xlab("") + ylab("") + theme(axis.text.x = element_text(angle = 90, vjust = 0.5, hjust=1))
ggplot(uk_census_2021_religion_merged, aes(fill=fct_reorder(dataset, value), x=reorder(key,-value),value, y=perc)) + geom_bar(position="dodge", stat ="identity", colour = "black") + scale_fill_brewer(palette = "Set1") + ggtitle("Religious Affiliation in the 2021 Census of England and Wales") + xlab("") + ylab("") + theme(axis.text.x = element_text(angle = 90, vjust = 0.5, hjust=1))
nomis_extract_census2021 <- readRDS(file = (here("example_data", "nomis_extract_census2021.rds")))
#| column: margin
uk_census_2021_religion_ethnicity <- select(nomis_extract_census2021, GEOGRAPHY_NAME, C2021_RELIGION_10_NAME, C2021_ETH_8_NAME, OBS_VALUE) # <1>
uk_census_2021_religion_ethnicity <- filter(uk_census_2021_religion_ethnicity, GEOGRAPHY_NAME=="England and Wales" & C2021_RELIGION_10_NAME != "Total" & C2021_ETH_8_NAME != "Total") # <2>
uk_census_2021_religion_ethnicity <- filter(uk_census_2021_religion_ethnicity, C2021_ETH_8_NAME != "White: English, Welsh, Scottish, Northern Irish or British" & C2021_ETH_8_NAME != "White: Irish" & C2021_ETH_8_NAME != "White: Gypsy or Irish Traveller, Roma or Other White") # <3>
ggplot(uk_census_2021_religion_ethnicity, aes(fill=C2021_ETH_8_NAME, x=C2021_RELIGION_10_NAME, y=OBS_VALUE)) + geom_bar(position="dodge", stat ="identity", colour = "black") + scale_fill_brewer(palette = "Set1") + ggtitle("Religious Affiliation in the 2021 Census of England and Wales") + xlab("") + ylab("") + theme(axis.text.x = element_text(angle = 90, vjust = 0.5, hjust=1)) # <4>
uk_census_2021_religion_ethnicity <- select(nomis_extract_census2021, GEOGRAPHY_NAME, C2021_RELIGION_10_NAME, C2021_ETH_8_NAME, OBS_VALUE) # <1>
uk_census_2021_religion_ethnicity <- filter(uk_census_2021_religion_ethnicity, GEOGRAPHY_NAME=="England and Wales" & C2021_RELIGION_10_NAME != "Total" & C2021_ETH_8_NAME != "Total") # <2>
uk_census_2021_religion_ethnicity <- filter(uk_census_2021_religion_ethnicity, C2021_ETH_8_NAME != "White: English, Welsh, Scottish, Northern Irish or British" & C2021_ETH_8_NAME != "White: Irish" & C2021_ETH_8_NAME != "White: Gypsy or Irish Traveller, Roma or Other White") # <3>
ggplot(uk_census_2021_religion_ethnicity, aes(fill=C2021_ETH_8_NAME, x=C2021_RELIGION_10_NAME, y=OBS_VALUE)) + geom_bar(position="dodge", stat ="identity", colour = "black") + scale_fill_brewer(palette = "Set1") + ggtitle("Religious Affiliation in the 2021 Census of England and Wales") + xlab("") + ylab("") + theme(axis.text.x = element_text(angle = 90, vjust = 0.5, hjust=1)) # <4>
#| column: margin
uk_census_2021_religion_ethnicity_white <- filter(uk_census_2021_religion_ethnicity, C2021_ETH_8_NAME == "White") # <1>
uk_census_2021_religion_ethnicity_nonwhite <- filter(uk_census_2021_religion_ethnicity, C2021_ETH_8_NAME != "White") # <2>
ggplot(uk_census_2021_religion_ethnicity_nonwhite, aes(fill=C2021_ETH_8_NAME, x=C2021_RELIGION_10_NAME, y=OBS_VALUE)) + geom_bar(position="dodge", stat ="identity", colour = "black") + scale_fill_brewer(palette = "Set1") + ggtitle("Religious Affiliation in the 2021 Census of England and Wales") + xlab("") + ylab("") + theme(axis.text.x = element_text(angle = 90, vjust = 0.5, hjust=1)) # <3>
ggplot(uk_census_2021_religion_ethnicity, aes(fill=C2021_ETH_8_NAME, x=C2021_RELIGION_10_NAME, y=OBS_VALUE), x=reorder(key,-value),value, y=perc)) + geom_bar(position="dodge", stat ="identity", colour = "black") + scale_fill_brewer(palette = "Set1") + ggtitle("Religious Affiliation in the 2021 Census of England and Wales") + xlab("") + ylab("") + theme(axis.text.x = element_text(angle = 90, vjust = 0.5, hjust=1)) # <4>
ggplot(uk_census_2021_religion_ethnicity, aes(fill=C2021_ETH_8_NAME, x=C2021_RELIGION_10_NAME, y=OBS_VALUE), x=reorder(key,-value),value, y=perc) + geom_bar(position="dodge", stat ="identity", colour = "black") + scale_fill_brewer(palette = "Set1") + ggtitle("Religious Affiliation in the 2021 Census of England and Wales") + xlab("") + ylab("") + theme(axis.text.x = element_text(angle = 90, vjust = 0.5, hjust=1)) # <4>
ggplot(uk_census_2021_religion_ethnicity, aes(fill=C2021_ETH_8_NAME, x=C2021_RELIGION_10_NAME, y=OBS_VALUE, x=reorder(key,-value),value, y=perc)) + geom_bar(position="dodge", stat ="identity", colour = "black") + scale_fill_brewer(palette = "Set1") + ggtitle("Religious Affiliation in the 2021 Census of England and Wales") + xlab("") + ylab("") + theme(axis.text.x = element_text(angle = 90, vjust = 0.5, hjust=1)) # <4>
ggplot(uk_census_2021_religion_ethnicity, aes(fill=C2021_ETH_8_NAME, x=C2021_RELIGION_10_NAME, y=OBS_VALUE) + geom_bar(position="dodge", stat ="identity", colour = "black") + scale_fill_brewer(palette = "Set1") + ggtitle("Religious Affiliation in the 2021 Census of England and Wales") + xlab("") + ylab("") + theme(axis.text.x = element_text(angle = 90, vjust = 0.5, hjust=1)) # <4>
ggplot(uk_census_2021_religion_ethnicity, aes(fill=C2021_ETH_8_NAME, x=C2021_RELIGION_10_NAME, y=OBS_VALUE)) +
scale_y_continuous(labels = percent_format()
ggplot(uk_census_2021_religion_ethnicity, aes(fill=C2021_ETH_8_NAME, x=C2021_RELIGION_10_NAME, y=OBS_VALUE)) +
ggplot(uk_census_2021_religion_ethnicity, aes(fill=C2021_ETH_8_NAME, x=C2021_RELIGION_10_NAME, y=OBS_VALUE)) +
geom_bar(position="dodge", stat ="identity", colour = "black") +
scale_fill_brewer(palette = "Set1") +
ggtitle("Religious Affiliation in the 2021 Census of England and Wales") +
xlab("") + ylab("") +
theme(axis.text.x = element_text(angle = 90, vjust = 0.5, hjust=1) +
scale_y_continuous(labels = percent_format())) # <4>
uk_census_2021_religion_ethnicity <- select(nomis_extract_census2021, GEOGRAPHY_NAME, C2021_RELIGION_10_NAME, C2021_ETH_8_NAME, OBS_VALUE) # <1>
uk_census_2021_religion_ethnicity <- filter(uk_census_2021_religion_ethnicity, GEOGRAPHY_NAME=="England and Wales" & C2021_RELIGION_10_NAME != "Total" & C2021_ETH_8_NAME != "Total") # <2>
uk_census_2021_religion_ethnicity <- filter(uk_census_2021_religion_ethnicity, C2021_ETH_8_NAME != "White: English, Welsh, Scottish, Northern Irish or British" & C2021_ETH_8_NAME != "White: Irish" & C2021_ETH_8_NAME != "White: Gypsy or Irish Traveller, Roma or Other White") # <3>
ggplot(uk_census_2021_religion_ethnicity, aes(fill=C2021_ETH_8_NAME, x=C2021_RELIGION_10_NAME, y=OBS_VALUE)) +
geom_bar(position="dodge", stat ="identity", colour = "black") +
scale_fill_brewer(palette = "Set1") +
ggtitle("Religious Affiliation in the 2021 Census of England and Wales") +
xlab("") + ylab("") +
theme(axis.text.x = element_text(angle = 90, vjust = 0.5, hjust=1) +
scale_y_continuous(labels = percent_format())) # <4>
library(scales)
ggplot(uk_census_2021_religion_ethnicity, aes(fill=C2021_ETH_8_NAME, x=C2021_RELIGION_10_NAME, y=OBS_VALUE)) +
geom_bar(position="dodge", stat ="identity", colour = "black") +
scale_fill_brewer(palette = "Set1") +
ggtitle("Religious Affiliation in the 2021 Census of England and Wales") +
xlab("") + ylab("") +
theme(axis.text.x = element_text(angle = 90, vjust = 0.5, hjust=1) +
scale_y_continuous(labels = percent_format())) # <4>
ggplot(uk_census_2021_religion_ethnicity, aes(fill=C2021_ETH_8_NAME, x=C2021_RELIGION_10_NAME, y=OBS_VALUE)) +
geom_bar(position="dodge", stat ="identity", colour = "black") +
scale_fill_brewer(palette = "Set1") +
ggtitle("Religious Affiliation in the 2021 Census of England and Wales") +
xlab("") + ylab("") +
theme(axis.text.x = element_text(angle = 90, vjust = 0.5, hjust=1) +
scale_y_continuous(labels = scales::percent_format())) # <4>
ggplot(uk_census_2021_religion_ethnicity, aes(fill=C2021_ETH_8_NAME, x=C2021_RELIGION_10_NAME, y=OBS_VALUE)) +
ggplot(uk_census_2021_religion_ethnicity, aes(fill=C2021_ETH_8_NAME, x=C2021_RELIGION_10_NAME, y=OBS_VALUE)) +
ggplot(uk_census_2021_religion_ethnicity, aes(fill=C2021_ETH_8_NAME, x=C2021_RELIGION_10_NAME, y=OBS_VALUE)) +
geom_bar(position="dodge", stat ="identity", colour = "black") +
scale_fill_brewer(palette = "Set1") +
ggtitle("Religious Affiliation in the 2021 Census of England and Wales") +
xlab("") + ylab("") +
theme(axis.text.x = element_text(angle = 90, vjust = 0.5, hjust=1) +
scale_x_discrete(labels = function(x) paste0(x, "%"))) # <4>
percent_format_custom <- function(x) {
paste0(formatC(as.numeric(x), format = "f", digits = 2), "%")
}
ggplot(uk_census_2021_religion_ethnicity, aes(fill=C2021_ETH_8_NAME, x=C2021_RELIGION_10_NAME, y=OBS_VALUE)) +
geom_bar(position="dodge", stat ="identity", colour = "black") +
scale_fill_brewer(palette = "Set1") +
ggtitle("Religious Affiliation in the 2021 Census of England and Wales") +
xlab("") + ylab("") +
theme(axis.text.x = element_text(angle = 90, vjust = 0.5, hjust=1) +
scale_x_discrete(labels = percent_format_custom)) # <4>
uk_census_2021_religion_ethnicity$OBS_VALUE <- percent(uk_census_2021_religion_ethnicity$OBS_VALUE / 100)
ggplot(uk_census_2021_religion_ethnicity, aes(fill=C2021_ETH_8_NAME, x=C2021_RELIGION_10_NAME, y=OBS_VALUE)) +
ggplot(uk_census_2021_religion_ethnicity, aes(fill=C2021_ETH_8_NAME, x=C2021_RELIGION_10_NAME, y=OBS_VALUE)) +
geom_bar(position="dodge", stat ="identity", colour = "black") +
scale_fill_brewer(palette = "Set1") +
ggtitle("Religious Affiliation in the 2021 Census of England and Wales") +
xlab("") + ylab("") +
theme(axis.text.x = element_text(angle = 90, vjust = 0.5, hjust=1)) # <4>
ggplot(uk_census_2021_religion_ethnicity, aes(fill=C2021_ETH_8_NAME, x=C2021_RELIGION_10_NAME, y=OBS_VALUE)) +
geom_bar(position="dodge", stat ="identity", colour = "black") +
scale_fill_brewer(palette = "Set1") +
ggtitle("Religious Affiliation in the 2021 Census of England and Wales") +
xlab("") + ylab("") +
theme(axis.text.x = element_text(angle = 90, vjust = 0.5, hjust=1)) # <4>
uk_census_2021_religion_ethnicity <- select(nomis_extract_census2021, GEOGRAPHY_NAME, C2021_RELIGION_10_NAME, C2021_ETH_8_NAME, OBS_VALUE) # <1>
uk_census_2021_religion_ethnicity <- filter(uk_census_2021_religion_ethnicity, GEOGRAPHY_NAME=="England and Wales" & C2021_RELIGION_10_NAME != "Total" & C2021_ETH_8_NAME != "Total") # <2>
uk_census_2021_religion_ethnicity <- filter(uk_census_2021_religion_ethnicity, C2021_ETH_8_NAME != "White: English, Welsh, Scottish, Northern Irish or British" & C2021_ETH_8_NAME != "White: Irish" & C2021_ETH_8_NAME != "White: Gypsy or Irish Traveller, Roma or Other White") # <3>
ggplot(uk_census_2021_religion_ethnicity, aes(fill=C2021_ETH_8_NAME, x=C2021_RELIGION_10_NAME, y=OBS_VALUE)) +
geom_bar(position="dodge", stat ="identity", colour = "black") +
scale_fill_brewer(palette = "Set1") +
ggtitle("Religious Affiliation in the 2021 Census of England and Wales") +
xlab("") + ylab("") +
theme(axis.text.x = element_text(angle = 90, vjust = 0.5, hjust=1)) # <4>
ggplot(uk_census_2021_religion_ethnicity, aes(fill=C2021_ETH_8_NAME, x=C2021_RELIGION_10_NAME, y=OBS_VALUE)) +
geom_bar(position="dodge", stat ="identity", colour = "black") +
scale_fill_brewer(palette = "Set1") +
scale_x_log10() +
ggtitle("Religious Affiliation in the 2021 Census of England and Wales") +
xlab("") + ylab("") +
theme(axis.text.x = element_text(angle = 90, vjust = 0.5, hjust=1)) # <4>
uk_census_2021_religion_ethnicity
uk_census_2021_religion_ethnicity <- uk_census_2021_religion_ethnicity %>%
group_by(C2021_RELIGION_10_NAME) %>%
mutate(Percentage = OBS_VALUE / sum(OBS_VALUE) * 100)
ggplot(uk_census_2021_religion_ethnicity, aes(fill=C2021_ETH_8_NAME, x=C2021_RELIGION_10_NAME, y=OBS_VALUE)) +
geom_bar(position="dodge", stat ="identity", colour = "black") +
scale_fill_brewer(palette = "Set1") +
ggtitle("Religious Affiliation in the 2021 Census of England and Wales") +
xlab("") + ylab("") +
theme(axis.text.x = element_text(angle = 90, vjust = 0.5, hjust=1)) # <4>
uk_census_2021_religion_ethnicity
ggplot(uk_census_2021_religion_ethnicity, aes(fill=C2021_ETH_8_NAME, x=C2021_RELIGION_10_NAME, y=Percentage)) +
geom_bar(position="dodge", stat ="identity", colour = "black") +
scale_fill_brewer(palette = "Set1") +
ggtitle("Religious Affiliation in the 2021 Census of England and Wales") +
xlab("") + ylab("") +
theme(axis.text.x = element_text(angle = 90, vjust = 0.5, hjust=1)) # <4>
#| column: margin
uk_census_2021_religion_ethnicity_white <- filter(uk_census_2021_religion_ethnicity, C2021_ETH_8_NAME == "White") # <1>
uk_census_2021_religion_ethnicity_nonwhite <- filter(uk_census_2021_religion_ethnicity, C2021_ETH_8_NAME != "White") # <2>
ggplot(uk_census_2021_religion_ethnicity_nonwhite, aes(fill=C2021_ETH_8_NAME, x=C2021_RELIGION_10_NAME, y=OBS_VALUE)) + geom_bar(position="dodge", stat ="identity", colour = "black") + scale_fill_brewer(palette = "Set1") + ggtitle("Religious Affiliation in the 2021 Census of England and Wales") + xlab("") + ylab("") + theme(axis.text.x = element_text(angle = 90, vjust = 0.5, hjust=1)) # <3>
ggplot(uk_census_2021_religion_ethnicity_nonwhite, aes(fill=C2021_ETH_8_NAME, x=C2021_RELIGION_10_NAME, y=Percentage)) + geom_bar(position="dodge", stat ="identity", colour = "black") + scale_fill_brewer(palette = "Set1") + ggtitle("Religious Affiliation in the 2021 Census of England and Wales") + xlab("") + ylab("") + theme(axis.text.x = element_text(angle = 90, vjust = 0.5, hjust=1)) # <3>
uk_census_2021_religion_ethnicity_white <- filter(uk_census_2021_religion_ethnicity, C2021_ETH_8_NAME == "White") # <1>
uk_census_2021_religion_ethnicity_nonwhite <- filter(uk_census_2021_religion_ethnicity, C2021_ETH_8_NAME != "White") # <2>
uk_census_2021_religion_ethnicity_nonwhite <- uk_census_2021_religion_ethnicity_nonwhite %>%
group_by(C2021_RELIGION_10_NAME) %>%
mutate(Percentage = OBS_VALUE / sum(OBS_VALUE) * 100) # <4>
ggplot(uk_census_2021_religion_ethnicity_nonwhite, aes(fill=C2021_ETH_8_NAME, x=C2021_RELIGION_10_NAME, y=Percentage)) + geom_bar(position="dodge", stat ="identity", colour = "black") + scale_fill_brewer(palette = "Set1") + ggtitle("Religious Affiliation in the 2021 Census of England and Wales") + xlab("") + ylab("") + theme(axis.text.x = element_text(angle = 90, vjust = 0.5, hjust=1)) # <3>
ggplot(uk_census_2021_religion_ethnicity_nonwhite, aes(fill=C2021_ETH_8_NAME, x=C2021_RELIGION_10_NAME, y=OBS_VALUE)) + geom_bar(position="dodge", stat ="identity", colour = "black") + scale_fill_brewer(palette = "Set1") + ggtitle("Religious Affiliation in the 2021 Census of England and Wales") + xlab("") + ylab("") + theme(axis.text.x = element_text(angle = 90, vjust = 0.5, hjust=1)) # <3>
ggplot(uk_census_2021_religion_ethnicity, aes(fill=C2021_ETH_8_NAME, x=C2021_RELIGION_10_NAME, y=OBS_VALUE)) +
geom_bar(position="dodge", stat ="identity", colour = "black") +
scale_fill_brewer(palette = "Set1") +
ggtitle("Religious Affiliation in the 2021 Census of England and Wales") +
xlab("") + ylab("") +
theme(axis.text.x = element_text(angle = 90, vjust = 0.5, hjust=1)) # <5>
ggplot(uk_census_2021_religion_ethnicity, aes(fill=C2021_ETH_8_NAME, x=C2021_RELIGION_10_NAME, y=Percentage)) +
geom_bar(position="dodge", stat ="identity", colour = "black") +
scale_fill_brewer(palette = "Set1") +
ggtitle("Religious Affiliation in the 2021 Census of England and Wales") +
xlab("") + ylab("") +
theme(axis.text.x = element_text(angle = 90, vjust = 0.5, hjust=1)) # <5>
View(uk_census_2021_religion_ethnicity)
# TODO - fix display here so that's display is the same for Percentage as it is for OBS_VALUE
uk_census_2021_religion_ethnicity <- uk_census_2021_religion_ethnicity %>%
group_by(C2021_ETH_8_NAME) %>%
mutate(Percentage = OBS_VALUE / sum(OBS_VALUE) * 100) # <4>
ggplot(uk_census_2021_religion_ethnicity, aes(fill=C2021_ETH_8_NAME, x=C2021_RELIGION_10_NAME, y=Percentage)) +
geom_bar(position="dodge", stat ="identity", colour = "black") +
scale_fill_brewer(palette = "Set1") +
ggtitle("Religious Affiliation in the 2021 Census of England and Wales") +
xlab("") + ylab("") +
theme(axis.text.x = element_text(angle = 90, vjust = 0.5, hjust=1)) # <5>
ggplot(uk_census_2021_religion_ethnicity, aes(fill=C2021_ETH_8_NAME, x=C2021_RELIGION_10_NAME, y=Obsvalue)) +
geom_bar(position="dodge", stat ="identity", colour = "black") +
scale_fill_brewer(palette = "Set1") +
ggtitle("Religious Affiliation in the 2021 Census of England and Wales") +
xlab("") + ylab("") +
theme(axis.text.x = element_text(angle = 90, vjust = 0.5, hjust=1)) # <5>
ggplot(uk_census_2021_religion_ethnicity, aes(fill=C2021_ETH_8_NAME, x=C2021_RELIGION_10_NAME, y=OBS_VALUE)) +
geom_bar(position="dodge", stat ="identity", colour = "black") +
scale_fill_brewer(palette = "Set1") +
ggtitle("Religious Affiliation in the 2021 Census of England and Wales") +
xlab("") + ylab("") +
theme(axis.text.x = element_text(angle = 90, vjust = 0.5, hjust=1)) # <5>
# TODO - fix display here so that's display is the same for Percentage as it is for OBS_VALUE
uk_census_2021_religion_ethnicity <- uk_census_2021_religion_ethnicity %>%
group_by(C2021_ETH_8_NAME) %>%
mutate(Percentage = OBS_VALUE / sum(OBS_VALUE) * 100) # <4>
ggplot(uk_census_2021_religion_ethnicity, aes(fill=C2021_ETH_8_NAME, x=C2021_RELIGION_10_NAME, y=OBS_VALUE)) +
geom_bar(position="dodge", stat ="identity", colour = "black") +
scale_fill_brewer(palette = "Set1") +
ggtitle("Religious Affiliation in the 2021 Census of England and Wales") +
xlab("") + ylab("") +
theme(axis.text.x = element_text(angle = 90, vjust = 0.5, hjust=1)) # <5>
ggplot(uk_census_2021_religion_ethnicity, aes(fill=C2021_ETH_8_NAME, x=C2021_RELIGION_10_NAME, y=Percentage)) +
geom_bar(position="dodge", stat ="identity", colour = "black") +
scale_fill_brewer(palette = "Set1") +
ggtitle("Religious Affiliation in the 2021 Census of England and Wales") +
xlab("") + ylab("") +
theme(axis.text.x = element_text(angle = 90, vjust = 0.5, hjust=1)) # <5>
ggplot(uk_census_2021_religion_ethnicity_nonwhite, aes(x=C2021_RELIGION_10_NAME, y=OBS_VALUE)) + geom_bar(position="dodge", stat ="identity", colour = "black") + facet_wrap(~C2021_ETH_8_NAME, ncol = 2) + scale_fill_brewer(palette = "Set1") + ggtitle("Religious Affiliation in the 2021 Census of England and Wales") + xlab("") + ylab("") + theme(axis.text.x = element_text(angle = 90, vjust = 0.5, hjust=1))
uk_census_2021_religion_ethnicity_white <- filter(uk_census_2021_religion_ethnicity, C2021_ETH_8_NAME == "White") # <1>
uk_census_2021_religion_ethnicity_nonwhite <- filter(uk_census_2021_religion_ethnicity, C2021_ETH_8_NAME != "White") # <2>
uk_census_2021_religion_ethnicity_nonwhite <- uk_census_2021_religion_ethnicity_nonwhite %>%
group_by(C2021_ETH_8_NAME) %>%
mutate(Percentage = OBS_VALUE / sum(OBS_VALUE) * 100) # <4>
ggplot(uk_census_2021_religion_ethnicity_nonwhite, aes(fill=C2021_ETH_8_NAME, x=C2021_RELIGION_10_NAME, y=OBS_VALUE)) + geom_bar(position="dodge", stat ="identity", colour = "black") + scale_fill_brewer(palette = "Set1") + ggtitle("Religious Affiliation in the 2021 Census of England and Wales") + xlab("") + ylab("") + theme(axis.text.x = element_text(angle = 90, vjust = 0.5, hjust=1)) # <3>
ggplot(uk_census_2021_religion_ethnicity_nonwhite, aes(fill=C2021_ETH_8_NAME, x=C2021_RELIGION_10_NAME, y=Percentage)) + geom_bar(position="dodge", stat ="identity", colour = "black") + scale_fill_brewer(palette = "Set1") + ggtitle("Religious Affiliation in the 2021 Census of England and Wales") + xlab("") + ylab("") + theme(axis.text.x = element_text(angle = 90, vjust = 0.5, hjust=1)) # <3>
uk_census_2021_religion_ethnicity_white <- filter(uk_census_2021_religion_ethnicity, C2021_ETH_8_NAME == "White") # <1>
uk_census_2021_religion_ethnicity_nonwhite <- filter(uk_census_2021_religion_ethnicity, C2021_ETH_8_NAME != "White") # <2>
ggplot(uk_census_2021_religion_ethnicity_nonwhite, aes(fill=C2021_ETH_8_NAME, x=C2021_RELIGION_10_NAME, y=OBS_VALUE)) + geom_bar(position="dodge", stat ="identity", colour = "black") + scale_fill_brewer(palette = "Set1") + ggtitle("Religious Affiliation in the 2021 Census of England and Wales") + xlab("") + ylab("") + theme(axis.text.x = element_text(angle = 90, vjust = 0.5, hjust=1)) # <3>
uk_census_2021_religion_ethnicity <- uk_census_2021_religion_ethnicity %>%
group_by(C2021_ETH_8_NAME) %>%
mutate(Percentage = OBS_VALUE / sum(OBS_VALUE) * 100)
ggplot(uk_census_2021_religion_ethnicity, aes(fill=C2021_ETH_8_NAME, x=C2021_RELIGION_10_NAME, y=OBS_VALUE)) +
geom_bar(position="dodge", stat ="identity", colour = "black") +
scale_fill_brewer(palette = "Set1") +
ggtitle("Religious Affiliation in the 2021 Census of England and Wales") +
xlab("") + ylab("") +
theme(axis.text.x = element_text(angle = 90, vjust = 0.5, hjust=1))
ggplot(uk_census_2021_religion_ethnicity, aes(fill=C2021_ETH_8_NAME, x=C2021_RELIGION_10_NAME, y=Percentage)) +
geom_bar(position="dodge", stat ="identity", colour = "black") +
scale_fill_brewer(palette = "Set1") +
ggtitle("Religious Affiliation in the 2021 Census of England and Wales") +
xlab("") + ylab("") +
theme(axis.text.x = element_text(angle = 90, vjust = 0.5, hjust=1))
ggplot(uk_census_2021_religion_ethnicity_nonwhite, aes(x=C2021_RELIGION_10_NAME, y=OBS_VALUE)) +
geom_bar(position="dodge", stat ="identity", colour = "black") +
facet_wrap(~C2021_ETH_8_NAME, ncol = 2) + scale_fill_brewer(palette = "Set1") +
ggtitle("Religious Affiliation in the 2021 Census of England and Wales") + xlab("") + ylab("") +
theme(axis.text.x = element_text(angle = 90, vjust = 0.5, hjust=1))
nomis_extract_census2001 <- readRDS(file = (here("example_data", "nomis_extract_census2001.rds")))
nomis_extract_census2011 <- readRDS(file = (here("example_data", "nomis_extract_census2011.rds")))
uk_census_2001_religion_ethnicity <- select(nomis_extract_census2001, GEOGRAPHY_NAME, C_RELPUK11_NAME, C_ETHHUK11_NAME, OBS_VALUE) # <1>
uk_census_2011_religion_ethnicity <- select(nomis_extract_census2011, GEOGRAPHY_NAME, C_RELPUK11_NAME, C_ETHPUK11_NAME, OBS_VALUE) # <1>
uk_census_2001_religion_ethnicity <- filter(uk_census_2001_religion_ethnicity, GEOGRAPHY_NAME=="England and Wales" & C_RELPUK11_NAME != "All categories: Religion") # <2>
uk_census_2011_religion_ethnicity <- filter(uk_census_2011_religion_ethnicity, GEOGRAPHY_NAME=="England and Wales" & C_RELPUK11_NAME != "All categories: Religion" & C_ETHPUK11_NAME != "All categories: Ethnic group") # <2>
uk_census_2001_religion_ethnicity <- uk_census_2001_religion_ethnicity %>% filter(grepl('Total', C_ETHHUK11_NAME)) # <3>
uk_census_2011_religion_ethnicity <- uk_census_2011_religion_ethnicity %>% filter(grepl('Total', C_ETHPUK11_NAME)) # <3>
uk_census_2011_religion_plot <- ggplot(uk_census_2011_religion_ethnicity, aes(x = C_RELPUK11_NAME, y = OBS_VALUE)) + geom_bar(stat = "identity") + theme(axis.text.x = element_text(angle = 90, vjust = 0.5, hjust=1))
uk_census_2001_religion_ethnicity$dataset <- c("2001") # <1>
uk_census_2011_religion_ethnicity$dataset <- c("2011") # <1>
uk_census_2021_religion_ethnicity$dataset <- c("2021") # <1>
names(uk_census_2001_religion_ethnicity) <- c("Geography", "Religion", "Ethnicity", "Value", "Year") # <2>
names(uk_census_2011_religion_ethnicity) <- c("Geography", "Religion", "Ethnicity", "Value", "Year") # <2>
names(uk_census_2021_religion_ethnicity) <- c("Geography", "Religion", "Ethnicity", "Value", "Year") # <2>
# Next we need to change the terms using mutate()
uk_census_2001_religion_ethnicity <- uk_census_2001_religion_ethnicity %>%
mutate(Ethnicity = str_replace_all(Ethnicity,
pattern = "^White: Total$", replacement = "White")) %>%
mutate(Ethnicity = str_replace_all(Ethnicity,
pattern = "^Mixed: Total$", replacement = "Mixed")) %>%
mutate(Ethnicity = str_replace_all(Ethnicity,
pattern = "^Asian: Total$", replacement = "Asian")) %>%
mutate(Ethnicity = str_replace_all(Ethnicity,
pattern = "^Black or Black British: Total$", replacement = "Black")) %>%
mutate(Ethnicity = str_replace_all(Ethnicity,
pattern = "^Chinese or Other ethnic group: Total$", replacement = "Other"))
uk_census_2011_religion_ethnicity <- uk_census_2011_religion_ethnicity %>%
mutate(Ethnicity = str_replace_all(Ethnicity,
pattern = "^White: Total$", replacement = "White")) %>%
mutate(Ethnicity = str_replace_all(Ethnicity,
pattern = "^Mixed/multiple ethnic group: Total$", replacement = "Mixed")) %>%
mutate(Ethnicity = str_replace_all(Ethnicity,
pattern = "^Asian/Asian British: Total$", replacement = "Asian")) %>%
mutate(Ethnicity = str_replace_all(Ethnicity,
pattern = "^Black/African/Caribbean/Black British: Total$", replacement = "Black")) %>%
mutate(Ethnicity = str_replace_all(Ethnicity,
pattern = "^Other ethnic group: Total$", replacement = "Other"))
uk_census_2021_religion_ethnicity <- uk_census_2021_religion_ethnicity %>%
mutate(Ethnicity = str_replace_all(Ethnicity,
pattern = "^White: Total$", replacement = "White")) %>%
mutate(Ethnicity = str_replace_all(Ethnicity,
pattern = "^Mixed or Multiple ethnic groups$", replacement = "Mixed")) %>%
mutate(Ethnicity = str_replace_all(Ethnicity,
pattern = "^Asian, Asian British or Asian Welsh$", replacement = "Asian")) %>%
mutate(Ethnicity = str_replace_all(Ethnicity,
pattern = "^Black, Black British, Black Welsh, Caribbean or African$", replacement = "Black")) %>%
mutate(Ethnicity = str_replace_all(Ethnicity,
pattern = "^Other ethnic group$", replacement = "Other"))
uk_census_2021_religion_ethnicity_percents <- uk_census_2021_religion_ethnicity %>%
group_by(C2021_ETH_8_NAME) %>%
mutate(Percentage = OBS_VALUE / sum(OBS_VALUE) * 100)
uk_census_2021_religion_ethnicity <- select(nomis_extract_census2021, GEOGRAPHY_NAME, C2021_RELIGION_10_NAME, C2021_ETH_8_NAME, OBS_VALUE) # <1>
uk_census_2021_religion_ethnicity <- filter(uk_census_2021_religion_ethnicity, GEOGRAPHY_NAME=="England and Wales" & C2021_RELIGION_10_NAME != "Total" & C2021_ETH_8_NAME != "Total") # <2>
uk_census_2021_religion_ethnicity <- filter(uk_census_2021_religion_ethnicity, C2021_ETH_8_NAME != "White: English, Welsh, Scottish, Northern Irish or British" & C2021_ETH_8_NAME != "White: Irish" & C2021_ETH_8_NAME != "White: Gypsy or Irish Traveller, Roma or Other White") # <3>
ggplot(uk_census_2021_religion_ethnicity, aes(fill=C2021_ETH_8_NAME, x=C2021_RELIGION_10_NAME, y=OBS_VALUE)) +
geom_bar(position="dodge", stat ="identity", colour = "black") +
scale_fill_brewer(palette = "Set1") +
ggtitle("Religious Affiliation in the 2021 Census of England and Wales") +
xlab("") + ylab("") +
theme(axis.text.x = element_text(angle = 90, vjust = 0.5, hjust=1)) # <4>
uk_census_2021_religion_ethnicity_white <- filter(uk_census_2021_religion_ethnicity, C2021_ETH_8_NAME == "White") # <1>
uk_census_2021_religion_ethnicity_nonwhite <- filter(uk_census_2021_religion_ethnicity, C2021_ETH_8_NAME != "White") # <2>
ggplot(uk_census_2021_religion_ethnicity_nonwhite, aes(fill=C2021_ETH_8_NAME, x=C2021_RELIGION_10_NAME, y=OBS_VALUE)) + geom_bar(position="dodge", stat ="identity", colour = "black") + scale_fill_brewer(palette = "Set1") + ggtitle("Religious Affiliation in the 2021 Census of England and Wales") + xlab("") + ylab("") + theme(axis.text.x = element_text(angle = 90, vjust = 0.5, hjust=1)) # <3>
uk_census_2021_religion_ethnicity_percents <- uk_census_2021_religion_ethnicity %>%
group_by(C2021_ETH_8_NAME) %>%
mutate(Percentage = OBS_VALUE / sum(OBS_VALUE) * 100)
ggplot(uk_census_2021_religion_ethnicity_percents, aes(fill=C2021_ETH_8_NAME, x=C2021_RELIGION_10_NAME, y=Percentage)) +
geom_bar(position="dodge", stat ="identity", colour = "black") +
scale_fill_brewer(palette = "Set1") +
ggtitle("Religious Affiliation in the 2021 Census of England and Wales") +
xlab("") + ylab("") +
theme(axis.text.x = element_text(angle = 90, vjust = 0.5, hjust=1))
ggplot(uk_census_2021_religion_ethnicity_nonwhite, aes(x=C2021_RELIGION_10_NAME, y=OBS_VALUE)) +
geom_bar(position="dodge", stat ="identity", colour = "black") +
facet_wrap(~C2021_ETH_8_NAME, ncol = 2) + scale_fill_brewer(palette = "Set1") +
ggtitle("Religious Affiliation in the 2021 Census of England and Wales") + xlab("") + ylab("") +
theme(axis.text.x = element_text(angle = 90, vjust = 0.5, hjust=1))
nomis_extract_census2001 <- readRDS(file = (here("example_data", "nomis_extract_census2001.rds")))
nomis_extract_census2011 <- readRDS(file = (here("example_data", "nomis_extract_census2011.rds")))
uk_census_2001_religion_ethnicity <- select(nomis_extract_census2001, GEOGRAPHY_NAME, C_RELPUK11_NAME, C_ETHHUK11_NAME, OBS_VALUE) # <1>
uk_census_2011_religion_ethnicity <- select(nomis_extract_census2011, GEOGRAPHY_NAME, C_RELPUK11_NAME, C_ETHPUK11_NAME, OBS_VALUE) # <1>
uk_census_2001_religion_ethnicity <- filter(uk_census_2001_religion_ethnicity, GEOGRAPHY_NAME=="England and Wales" & C_RELPUK11_NAME != "All categories: Religion") # <2>
uk_census_2011_religion_ethnicity <- filter(uk_census_2011_religion_ethnicity, GEOGRAPHY_NAME=="England and Wales" & C_RELPUK11_NAME != "All categories: Religion" & C_ETHPUK11_NAME != "All categories: Ethnic group") # <2>
uk_census_2001_religion_ethnicity <- uk_census_2001_religion_ethnicity %>% filter(grepl('Total', C_ETHHUK11_NAME)) # <3>
uk_census_2011_religion_ethnicity <- uk_census_2011_religion_ethnicity %>% filter(grepl('Total', C_ETHPUK11_NAME)) # <3>
uk_census_2011_religion_plot <- ggplot(uk_census_2011_religion_ethnicity, aes(x = C_RELPUK11_NAME, y = OBS_VALUE)) + geom_bar(stat = "identity") + theme(axis.text.x = element_text(angle = 90, vjust = 0.5, hjust=1))
uk_census_2001_religion_ethnicity$dataset <- c("2001") # <1>
uk_census_2011_religion_ethnicity$dataset <- c("2011") # <1>
uk_census_2021_religion_ethnicity$dataset <- c("2021") # <1>
names(uk_census_2001_religion_ethnicity) <- c("Geography", "Religion", "Ethnicity", "Value", "Year") # <2>
names(uk_census_2011_religion_ethnicity) <- c("Geography", "Religion", "Ethnicity", "Value", "Year") # <2>
names(uk_census_2021_religion_ethnicity) <- c("Geography", "Religion", "Ethnicity", "Value", "Year") # <2>
# Next we need to change the terms using mutate()
uk_census_2001_religion_ethnicity <- uk_census_2001_religion_ethnicity %>%
mutate(Ethnicity = str_replace_all(Ethnicity,
pattern = "^White: Total$", replacement = "White")) %>%
mutate(Ethnicity = str_replace_all(Ethnicity,
pattern = "^Mixed: Total$", replacement = "Mixed")) %>%
mutate(Ethnicity = str_replace_all(Ethnicity,
pattern = "^Asian: Total$", replacement = "Asian")) %>%
mutate(Ethnicity = str_replace_all(Ethnicity,
pattern = "^Black or Black British: Total$", replacement = "Black")) %>%
mutate(Ethnicity = str_replace_all(Ethnicity,
pattern = "^Chinese or Other ethnic group: Total$", replacement = "Other"))
uk_census_2011_religion_ethnicity <- uk_census_2011_religion_ethnicity %>%
mutate(Ethnicity = str_replace_all(Ethnicity,
pattern = "^White: Total$", replacement = "White")) %>%
mutate(Ethnicity = str_replace_all(Ethnicity,
pattern = "^Mixed/multiple ethnic group: Total$", replacement = "Mixed")) %>%
mutate(Ethnicity = str_replace_all(Ethnicity,
pattern = "^Asian/Asian British: Total$", replacement = "Asian")) %>%
mutate(Ethnicity = str_replace_all(Ethnicity,
pattern = "^Black/African/Caribbean/Black British: Total$", replacement = "Black")) %>%
mutate(Ethnicity = str_replace_all(Ethnicity,
pattern = "^Other ethnic group: Total$", replacement = "Other"))
uk_census_2021_religion_ethnicity <- uk_census_2021_religion_ethnicity %>%
mutate(Ethnicity = str_replace_all(Ethnicity,
pattern = "^White: Total$", replacement = "White")) %>%
mutate(Ethnicity = str_replace_all(Ethnicity,
pattern = "^Mixed or Multiple ethnic groups$", replacement = "Mixed")) %>%
mutate(Ethnicity = str_replace_all(Ethnicity,
pattern = "^Asian, Asian British or Asian Welsh$", replacement = "Asian")) %>%
mutate(Ethnicity = str_replace_all(Ethnicity,
pattern = "^Black, Black British, Black Welsh, Caribbean or African$", replacement = "Black")) %>%
mutate(Ethnicity = str_replace_all(Ethnicity,
pattern = "^Other ethnic group$", replacement = "Other"))
uk_census_merged_religion_ethnicity <- rbind(uk_census_2021_religion_ethnicity, uk_census_2011_religion_ethnicity)
uk_census_merged_religion_ethnicity <- rbind(uk_census_merged_religion_ethnicity, uk_census_2001_religion_ethnicity)
uk_census_merged_religion_ethnicity_nonwhite <- filter(uk_census_merged_religion_ethnicity, Ethnicity != "White")
ggplot(uk_census_merged_religion_ethnicity_nonwhite, aes(fill=Year, x=Religion, y=Value)) + geom_bar(position="dodge", stat ="identity", colour = "black") + facet_wrap(~Ethnicity, ncol = 2) + scale_fill_brewer(palette = "Set1") + ggtitle("Religious Affiliation in the 2001-2021 Census of England and Wales") + xlab("") + ylab("") + theme(axis.text.x = element_text(angle = 90, vjust = 0.5, hjust=1))
ggplot(uk_census_merged_religion_ethnicity_nonwhite, aes(fill=Year, x=Religion, y=Value)) +
geom_bar(position="dodge", stat ="identity", colour = "black") +
facet_wrap(~Ethnicity, ncol = 2) +
scale_fill_brewer(palette = "Set1") +
ggtitle("Religious Affiliation in the 2001-2021 Census of England and Wales") +
xlab("") + ylab("") +
theme(axis.text.x = element_text(angle = 90, vjust = 0.5, hjust=1))
library(scales) |> suppressPackageStartupMessages()
ggplot(uk_census_merged_religion_ethnicity_nonwhite, aes(fill=Year, x=Religion, y=Value)) + geom_bar(position="dodge", stat ="identity", colour = "black") + facet_wrap(~Ethnicity, ncol = 2) + scale_fill_brewer(palette = "Set1") + scale_y_continuous(labels = unit_format(unit = "M", scale = 1e-6), breaks = breaks_extended(8)) + ggtitle("Religious Affiliation in the 2001-2021 Census of England and Wales") + xlab("") + ylab("") + theme(axis.text.x = element_text(angle = 90, vjust = 0.5, hjust=1))
uk_census_merged_religion_ethnicity <- uk_census_merged_religion_ethnicity %>%
group_by(Ethnicity, Year) %>%
dplyr::mutate(Percent = Value/sum(Value))
ggplot(uk_census_merged_religion_ethnicity, aes(fill=Year, x=Religion, y=Percent)) + geom_bar(position="dodge", stat ="identity", colour = "black") + facet_wrap(~Ethnicity, scales="free_x") + scale_fill_brewer(palette = "Set1") + scale_y_continuous(labels = scales::percent) + ggtitle("Religious Affiliation in the 2001-2021 Censuses of England and Wales") + xlab("") + ylab("") + theme(axis.text.x = element_text(angle = 90, vjust = 0.5, hjust=1))
uk_census_merged_religion_ethnicity_plot <- ggplot(uk_census_merged_religion_ethnicity, aes(fill=Year, x=Religion, y=Percent)) +
geom_bar(position="dodge", stat ="identity", colour = "black") +
facet_wrap(~Ethnicity, scales="free_x") +
scale_fill_brewer(palette = "Set1") +
scale_y_continuous(labels = scales::percent) +
ggtitle("Religious Affiliation in the 2001-2021 Censuses of England and Wales") +
xlab("") + ylab("") +
theme(axis.text.x = element_text(angle = 90, vjust = 0.5, hjust=1))
ggsave("figures/chart.png", plot=uk_census_merged_religion_ethnicity_plot, width = 8, height = 10, units=c("in"))
uk_census_merged_religion_ethnicity_plot
setwd("/Users/kidwellj/gits/hacking_religion_textbook/hacking_religion")

File diff suppressed because it is too large Load diff

Binary file not shown.

After

Width:  |  Height:  |  Size: 31 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 50 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 50 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 58 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 60 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 66 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 68 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 71 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 63 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 65 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 59 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 71 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 81 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 100 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 26 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 23 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 25 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 24 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 29 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 42 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 42 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 88 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 90 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 99 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 102 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 100 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 92 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 94 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 47 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 100 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 112 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 127 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 14 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 17 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 19 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 19 KiB

677
hacking_religion/index.html Normal file
View file

@ -0,0 +1,677 @@
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en"><head>
<meta charset="utf-8">
<meta name="generator" content="quarto-1.4.551">
<meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=yes">
<meta name="author" content="Jeremy H. Kidwell">
<meta name="dcterms.date" content="2023-10-16">
<title>Hacking Religion: TRS &amp; Data Science in Action</title>
<style>
code{white-space: pre-wrap;}
span.smallcaps{font-variant: small-caps;}
div.columns{display: flex; gap: min(4vw, 1.5em);}
div.column{flex: auto; overflow-x: auto;}
div.hanging-indent{margin-left: 1.5em; text-indent: -1.5em;}
ul.task-list{list-style: none;}
ul.task-list li input[type="checkbox"] {
width: 0.8em;
margin: 0 0.8em 0.2em -1em; /* quarto-specific, see https://github.com/quarto-dev/quarto-cli/issues/4556 */
vertical-align: middle;
}
</style>
<script src="site_libs/quarto-nav/quarto-nav.js"></script>
<script src="site_libs/quarto-nav/headroom.min.js"></script>
<script src="site_libs/clipboard/clipboard.min.js"></script>
<script src="site_libs/quarto-search/autocomplete.umd.js"></script>
<script src="site_libs/quarto-search/fuse.min.js"></script>
<script src="site_libs/quarto-search/quarto-search.js"></script>
<meta name="quarto:offset" content="./">
<link href="./chapter_1.html" rel="next">
<script src="site_libs/quarto-html/quarto.js"></script>
<script src="site_libs/quarto-html/popper.min.js"></script>
<script src="site_libs/quarto-html/tippy.umd.min.js"></script>
<script src="site_libs/quarto-html/anchor.min.js"></script>
<link href="site_libs/quarto-html/tippy.css" rel="stylesheet">
<link href="site_libs/quarto-html/quarto-syntax-highlighting.css" rel="stylesheet" id="quarto-text-highlighting-styles">
<script src="site_libs/bootstrap/bootstrap.min.js"></script>
<link href="site_libs/bootstrap/bootstrap-icons.css" rel="stylesheet">
<link href="site_libs/bootstrap/bootstrap.min.css" rel="stylesheet" id="quarto-bootstrap" data-mode="light">
<script id="quarto-search-options" type="application/json">{
"location": "sidebar",
"copy-button": false,
"collapse-after": 3,
"panel-placement": "start",
"type": "textbox",
"limit": 50,
"keyboard-shortcut": [
"f",
"/",
"s"
],
"show-item-context": false,
"language": {
"search-no-results-text": "No results",
"search-matching-documents-text": "matching documents",
"search-copy-link-title": "Copy link to search",
"search-hide-matches-text": "Hide additional matches",
"search-more-match-text": "more match in this document",
"search-more-matches-text": "more matches in this document",
"search-clear-button-title": "Clear",
"search-text-placeholder": "",
"search-detached-cancel-button-title": "Cancel",
"search-submit-button-title": "Submit",
"search-label": "Search"
}
}</script>
</head>
<body class="nav-sidebar floating">
<div id="quarto-search-results"></div>
<header id="quarto-header" class="headroom fixed-top">
<nav class="quarto-secondary-nav">
<div class="container-fluid d-flex">
<button type="button" class="quarto-btn-toggle btn" data-bs-toggle="collapse" data-bs-target=".quarto-sidebar-collapse-item" aria-controls="quarto-sidebar" aria-expanded="false" aria-label="Toggle sidebar navigation" onclick="if (window.quartoToggleHeadroom) { window.quartoToggleHeadroom(); }">
<i class="bi bi-layout-text-sidebar-reverse"></i>
</button>
<nav class="quarto-page-breadcrumbs" aria-label="breadcrumb"><ol class="breadcrumb"><li class="breadcrumb-item"><a href="./index.html">Introduction: Hacking Religion</a></li></ol></nav>
<a class="flex-grow-1" role="button" data-bs-toggle="collapse" data-bs-target=".quarto-sidebar-collapse-item" aria-controls="quarto-sidebar" aria-expanded="false" aria-label="Toggle sidebar navigation" onclick="if (window.quartoToggleHeadroom) { window.quartoToggleHeadroom(); }">
</a>
<button type="button" class="btn quarto-search-button" aria-label="" onclick="window.quartoOpenSearch();">
<i class="bi bi-search"></i>
</button>
</div>
</nav>
</header>
<!-- content -->
<div id="quarto-content" class="quarto-container page-columns page-rows-contents page-layout-article">
<!-- sidebar -->
<nav id="quarto-sidebar" class="sidebar collapse collapse-horizontal quarto-sidebar-collapse-item sidebar-navigation floating overflow-auto">
<div class="pt-lg-2 mt-2 text-left sidebar-header">
<div class="sidebar-title mb-0 py-0">
<a href="./">Hacking Religion: TRS &amp; Data Science in Action</a>
</div>
</div>
<div class="mt-2 flex-shrink-0 align-items-center">
<div class="sidebar-search">
<div id="quarto-search" class="" title="Search"></div>
</div>
</div>
<div class="sidebar-menu-container">
<ul class="list-unstyled mt-1">
<li class="sidebar-item">
<div class="sidebar-item-container">
<a href="./index.html" class="sidebar-item-text sidebar-link active">
<span class="menu-text">Introduction: Hacking Religion</span></a>
</div>
</li>
<li class="sidebar-item">
<div class="sidebar-item-container">
<a href="./chapter_1.html" class="sidebar-item-text sidebar-link">
<span class="menu-text"><span class="chapter-number">1</span>&nbsp; <span class="chapter-title">Set up local workspace:</span></span></a>
</div>
</li>
<li class="sidebar-item">
<div class="sidebar-item-container">
<a href="./chapter_2.html" class="sidebar-item-text sidebar-link">
<span class="menu-text"><span class="chapter-number">2</span>&nbsp; <span class="chapter-title">Different ways to measure religion using data science</span></span></a>
</div>
</li>
<li class="sidebar-item">
<div class="sidebar-item-container">
<a href="./chapter_3.html" class="sidebar-item-text sidebar-link">
<span class="menu-text"><span class="chapter-number">3</span>&nbsp; <span class="chapter-title">Mapping churches: geospatial data science</span></span></a>
</div>
</li>
<li class="sidebar-item">
<div class="sidebar-item-container">
<a href="./chapter_4.html" class="sidebar-item-text sidebar-link">
<span class="menu-text"><span class="chapter-number">4</span>&nbsp; <span class="chapter-title">Data scraping, corpus analysis and wordclouds</span></span></a>
</div>
</li>
<li class="sidebar-item">
<div class="sidebar-item-container">
<a href="./chapter_5.html" class="sidebar-item-text sidebar-link">
<span class="menu-text"><span class="chapter-number">5</span>&nbsp; <span class="chapter-title">Whats next?</span></span></a>
</div>
</li>
<li class="sidebar-item">
<div class="sidebar-item-container">
<a href="./summary.html" class="sidebar-item-text sidebar-link">
<span class="menu-text"><span class="chapter-number">6</span>&nbsp; <span class="chapter-title">Summary</span></span></a>
</div>
</li>
<li class="sidebar-item">
<div class="sidebar-item-container">
<a href="./references.html" class="sidebar-item-text sidebar-link">
<span class="menu-text">References</span></a>
</div>
</li>
</ul>
</div>
</nav>
<div id="quarto-sidebar-glass" class="quarto-sidebar-collapse-item" data-bs-toggle="collapse" data-bs-target=".quarto-sidebar-collapse-item"></div>
<!-- margin-sidebar -->
<div id="quarto-margin-sidebar" class="sidebar margin-sidebar">
<nav id="TOC" role="doc-toc" class="toc-active">
<h2 id="toc-title">Table of contents</h2>
<ul>
<li><a href="#introduction-hacking-religion" id="toc-introduction-hacking-religion" class="nav-link active" data-scroll-target="#introduction-hacking-religion">Introduction: Hacking Religion</a>
<ul class="collapse">
<li><a href="#why-this-book" id="toc-why-this-book" class="nav-link" data-scroll-target="#why-this-book">Why this book?</a></li>
<li><a href="#the-hacker-way" id="toc-the-hacker-way" class="nav-link" data-scroll-target="#the-hacker-way">The hacker way</a></li>
<li><a href="#learning-to-code-my-way" id="toc-learning-to-code-my-way" class="nav-link" data-scroll-target="#learning-to-code-my-way">Learning to code: my way</a></li>
<li><a href="#getting-set-up" id="toc-getting-set-up" class="nav-link" data-scroll-target="#getting-set-up">Getting set up</a></li>
</ul></li>
</ul>
</nav>
</div>
<!-- main -->
<main class="content" id="quarto-document-content">
<header id="title-block-header" class="quarto-title-block default">
<div class="quarto-title">
<h1 class="title">Hacking Religion: TRS &amp; Data Science in Action</h1>
</div>
<div class="quarto-title-meta">
<div>
<div class="quarto-title-meta-heading">Author</div>
<div class="quarto-title-meta-contents">
<p>Jeremy H. Kidwell </p>
</div>
</div>
<div>
<div class="quarto-title-meta-heading">Published</div>
<div class="quarto-title-meta-contents">
<p class="date">October 16, 2023</p>
</div>
</div>
</div>
</header>
<section id="introduction-hacking-religion" class="level1 unnumbered">
<h1 class="unnumbered">Introduction: Hacking Religion</h1>
<section id="why-this-book" class="level2">
<h2 class="anchored" data-anchor-id="why-this-book">Why this book?</h2>
<p>Data science is quickly consolidating as a new field, with new tools and user communities emerging every week. At the same time academic research has opened up into new interdisciplinary vistas, with experts crossing over into new fields, transgressing disciplinary boundaries and deploying tools in new and unexpected ways to develop knowledge. There are many gaps yet to be filled, but one which I found to be particularly glaring is the lack of applied data science documentation around the subject of religion. On one hand, scholars who are working with cutting edge theory seldom pick up these emerging tools of data science. On the other hand, data scientists rarely go beyond dabbling in religious themes, leaving quite a lot of really interesting theoretical research untouched. This book aims to bring these two things together: introducing the tools of data science in an applied way, whilst introducing some of the complexities and cutting edge theories which help us to conceptualise and frame our understanding of this knowledge regarding religion in the world around us.</p>
</section>
<section id="the-hacker-way" class="level2">
<h2 class="anchored" data-anchor-id="the-hacker-way">The hacker way</h2>
<p>Its worth emphasising at the outset that this isnt meant to be a generic data science book. My own training as a researcher lies in the field of religious ethics, and my engagement with digital technology has, from the very start, been a context for exploring matters of personal values and social action. A fair bit of ink has been spilled in books, magazines, blogs and zines unpacking what exactly it means to be a “hacker”. Pressing beyond some of the more superficial cultural stereotypes, I want to explain a bit here about how hacking can be a much more substantial vision for ethical engagement with technology and social transformation.</p>
<p>Back in the 1980s Steven Levy tried to capture some of this in his book “Hackers: Heroes of the Computer Revolution”. As Levy put it, the “hacker ethic” included: (1) sharing, (2) openness, (3) decentralisation, (4) free access to computers and (5) world improvement. The key point here is that hacking isnt just about writing and breaking code, or testing and finding weaknesses in computer systems and networks. There is often a more substantial underpinning ethical code which dovetails with on-the-surface matters of curiosity and craft.</p>
<p>This emphasis on ethics is especially important when were doing data science because this kind of research work will put you in positions of influence. You might think this seems a bit overstated, but it never ceases to amaze me how much bringing a bar chart which succinctly shows a social trend can sway a conversation or decision making process. There is something unusually persuasive that comes with the combination of aesthetics, data and storytelling. Ive met many people who have come to data science out of a desire to bring about social transformation in some sphere of life. People want to use technology and communication to make the world better. However, its possible that this can quickly get out of hand. With this in mind, Ive found that it can be important to have a clear sense of the convictions that guide your work in this field: a “hacker code” of sorts. Here are the principles that I have settled on in my own practice of “hacking” religion:</p>
<ol type="1">
<li><em>Tell the truth</em>: be candid about your limits, use visualisation responsibly</li>
<li><em>Work transparently</em>: open data, open code</li>
<li><em>Work in community</em>: draw others in by producing reproducible research</li>
<li><em>Work with reality</em> and learn by doing</li>
</ol>
<p>It never ceases to amaze me how often people think that, when theyre working for something they think is important it is acceptable to conceal bad news or amplify good or compelling information beyond its real scope. There are always consequences, eventually. When people realise youve been misleading or manipulating them your platform and credibility will evaporate. Good work mixed with bad will all get tossed out. And sometimes, our convictions can lead us beyond an accurate and true apprehension of the situation we are focussed on in research.</p>
<p>Presenting through “facts” an argument can become unnaturally compelling. Wrapping those facts up in something that uses colour, line and shape in a way that is aesthetically pleasing, even beautiful, enhances this allure even further. As you craft your own set of hacker principles, its vitally important that you always strive to tell the truth. This includes a willingness to acknowledge the limits of your information, and to share the whole set of information. The easiest way to do this is to work with visualation in a responsible way (Ill get into this a bit more in Chapter 1) and to open up your data and code to scrutiny. By allowing others to try, criticise, edit, and reappropriate your code and data in their own ways, you contribute to knowledge and help to build up a community of accountability. The upside of this is that its also a lot more fun and interesting to work alongside others.</p>
<p>Far too often, scholarly research (and theology) has been criticised for being disconnected from reality, making abstract pie-in-the-sky claims about how life should be lived. When exposed to the uncomfortable pressures of reality, these claims can crumble, or even turn sinister. One of the upsides of working with empirical research is that you have a chance to engage with the real world. For this reason, I love to do ethics in a way that arises - bottom-up - from real world experiences and relationships. Theres also the potential (at least in the best case scenario) that when we make choices based on reliable information drawn from everyday reality our policy and culture can be more resilient and accountable. This also works well with the hacker ethos of “learning by doing” and its this approach that guides my approach in this book. This isnt just a book about data analysis, Im proposing an approach which might be thought of as research-as-code, where you write out instructions to execute the various steps of work. The upside of this is that other researchers can learn from your work, correct and build on it as part of an intellectual commons. It takes a bit more time to learn and set things up, but the upside is that youll gain access to a set of tools and a research philosophy which is much more powerful.</p>
<p>Ill return to these principles periodically as we work through the coding and data in this book.</p>
</section>
<section id="learning-to-code-my-way" class="level2">
<h2 class="anchored" data-anchor-id="learning-to-code-my-way">Learning to code: my way</h2>
<p>Alongside these guiding principles, its also worth saying a bit about how I like to design teaching and learning. I remember when I was first starting out, and gathered coding manuals to read and learn from. They all tended to spend the first several hundred pages on theory, how you form an integer, data structures, subroutines, the logical structure of algorithms etc. etc. It was usually weeks of reading before I got to actually <em>do</em> anything. I know some people may prefer this approach, but I prefer a problem-focussed approach to learning. Give me something that is broken, or a problem to solve, which engages the things I want to figure out and the motivation for learning just comes much more naturally. And we know from research in cognitive science that these kinds of problem-focussed approaches can tend to faciliate faster learning and better retention. It will be helpful for you to be aware of this approach when you get into the book as it explains some of the editorial choices Ive made and the way Ive structured things.</p>
<p>Each chapter focusses on a series of <em>problems</em> which are particularly salient for the use of data science to conduct research into religion. These problems will be my focal point, guiding choices of specific aspects of programming to introduce to you as we work our way around that dataset and some of the crucial questions that arise in terms of how we handle it. If you find this approach unsatisfying, luckily there are a number of really terrific guides which lay things out slowly and methodically and I will explicitly signpost some of these along the way so that you can do a “deep dive” when you feel like it. You can also find a list of resources in Appendix B to this book. Otherwise, Ill take an accelerated approach to this introduction to data science in R. I expect that you will identify adjacent resources and perhaps even come up with your own creative approaches along the way, which incidentally is how real data science tends to work in practice.</p>
<p>There are a range of terrific textbooks which cover all these elements in greater depth and more slowly. In particular, Id recommend that many readers will want to check out Hadley Wickhams “<a href="https://r4ds.hadley.nz/">R For Data Science</a>” book. Ill include marginal notes in this guide pointing to sections of that book, and a few others which unpack the basic mechanics of R in more detail.</p>
</section>
<section id="getting-set-up" class="level2">
<h2 class="anchored" data-anchor-id="getting-set-up">Getting set up</h2>
<p>Every single tool, programming language and data set we refer to in this book is free and open source. These tools have been produced by professionals and volunteers who are passionate about data science and research and want to share it with the world, and in order to do this (and following the “hacker way”) theyve made these tools freely available. This also means that you arent restricted to a specific proprietary, expensive, or unavailable piece of software to do this work. Ill make a few opinionated recommendations here based on my own preferences and experience, but its really up to your own style and approach. In fact, given that this is an open source textbook, you can even propose additions to this chapter online sharing other tools youve found that you want to share with others.</p>
<p>There are, right now, primarily two languages that statisticians and data scientists use for this kind of programmatic data science: python and R. Each language has its merits and I wont rehash the debates between various factions. For this book, well be using the R language. This is, in part, because Ive found that the R user community and libraries tend to scale a bit better for the work that Im commending in this book. However, its entirely possible that one could use python for all these exercises, and Ill release a future version of this volume outlining python approaches to hacking religion.</p>
<p>Bearing this in mind, the first step youll need to take is to download and install R. You can find instructions and install packages for a wide range of hardware on a key resource online for R programmers: The Comprehensive R Archive Network (or “CRAN”): https://cran.rstudio.com. Once youve installed R, youve got some choices to make about the kind of programming environment youd like to use. You can just use a plain text editor like <code>textedit</code> to write your code and then execute your programs using the R software youve just installed. However, most users, myself included, tend to use an integrated development environment (or “IDE”). This is usually another software package with a guided user interface and some visual elements that make it faster to write and test your code. Some IDE packages will have built-in reference tools so you can look up options for libraries you use in your code. They will allow you to visualise the results of your code execution and perhaps most important of all, will enable you to execute your programs line by line so you can spot errors more quickly (we call this “debugging”). The two most popular IDE platforms for R coding at the time of writing this textbook are RStudio and Visual Studio. You should download and try out both and stick with your favourite, as the differences are largely aesthetic. I use a combination of RStudio and an enhanced plain text editor “Sublime Text” for my coding.</p>
<p>Once you have R and your pick of an IDE, you are ready to go! Proceed to the next chapter and well dive right in and get started!</p>
</section>
</section>
</main> <!-- /main -->
<script id="quarto-html-after-body" type="application/javascript">
window.document.addEventListener("DOMContentLoaded", function (event) {
const toggleBodyColorMode = (bsSheetEl) => {
const mode = bsSheetEl.getAttribute("data-mode");
const bodyEl = window.document.querySelector("body");
if (mode === "dark") {
bodyEl.classList.add("quarto-dark");
bodyEl.classList.remove("quarto-light");
} else {
bodyEl.classList.add("quarto-light");
bodyEl.classList.remove("quarto-dark");
}
}
const toggleBodyColorPrimary = () => {
const bsSheetEl = window.document.querySelector("link#quarto-bootstrap");
if (bsSheetEl) {
toggleBodyColorMode(bsSheetEl);
}
}
toggleBodyColorPrimary();
const icon = "";
const anchorJS = new window.AnchorJS();
anchorJS.options = {
placement: 'right',
icon: icon
};
anchorJS.add('.anchored');
const isCodeAnnotation = (el) => {
for (const clz of el.classList) {
if (clz.startsWith('code-annotation-')) {
return true;
}
}
return false;
}
const clipboard = new window.ClipboardJS('.code-copy-button', {
text: function(trigger) {
const codeEl = trigger.previousElementSibling.cloneNode(true);
for (const childEl of codeEl.children) {
if (isCodeAnnotation(childEl)) {
childEl.remove();
}
}
return codeEl.innerText;
}
});
clipboard.on('success', function(e) {
// button target
const button = e.trigger;
// don't keep focus
button.blur();
// flash "checked"
button.classList.add('code-copy-button-checked');
var currentTitle = button.getAttribute("title");
button.setAttribute("title", "Copied!");
let tooltip;
if (window.bootstrap) {
button.setAttribute("data-bs-toggle", "tooltip");
button.setAttribute("data-bs-placement", "left");
button.setAttribute("data-bs-title", "Copied!");
tooltip = new bootstrap.Tooltip(button,
{ trigger: "manual",
customClass: "code-copy-button-tooltip",
offset: [0, -8]});
tooltip.show();
}
setTimeout(function() {
if (tooltip) {
tooltip.hide();
button.removeAttribute("data-bs-title");
button.removeAttribute("data-bs-toggle");
button.removeAttribute("data-bs-placement");
}
button.setAttribute("title", currentTitle);
button.classList.remove('code-copy-button-checked');
}, 1000);
// clear code selection
e.clearSelection();
});
var localhostRegex = new RegExp(/^(?:http|https):\/\/localhost\:?[0-9]*\//);
var mailtoRegex = new RegExp(/^mailto:/);
var filterRegex = new RegExp('/' + window.location.host + '/');
var isInternal = (href) => {
return filterRegex.test(href) || localhostRegex.test(href) || mailtoRegex.test(href);
}
// Inspect non-navigation links and adorn them if external
var links = window.document.querySelectorAll('a[href]:not(.nav-link):not(.navbar-brand):not(.toc-action):not(.sidebar-link):not(.sidebar-item-toggle):not(.pagination-link):not(.no-external):not([aria-hidden]):not(.dropdown-item):not(.quarto-navigation-tool)');
for (var i=0; i<links.length; i++) {
const link = links[i];
if (!isInternal(link.href)) {
// undo the damage that might have been done by quarto-nav.js in the case of
// links that we want to consider external
if (link.dataset.originalHref !== undefined) {
link.href = link.dataset.originalHref;
}
}
}
function tippyHover(el, contentFn, onTriggerFn, onUntriggerFn) {
const config = {
allowHTML: true,
maxWidth: 500,
delay: 100,
arrow: false,
appendTo: function(el) {
return el.parentElement;
},
interactive: true,
interactiveBorder: 10,
theme: 'quarto',
placement: 'bottom-start',
};
if (contentFn) {
config.content = contentFn;
}
if (onTriggerFn) {
config.onTrigger = onTriggerFn;
}
if (onUntriggerFn) {
config.onUntrigger = onUntriggerFn;
}
window.tippy(el, config);
}
const noterefs = window.document.querySelectorAll('a[role="doc-noteref"]');
for (var i=0; i<noterefs.length; i++) {
const ref = noterefs[i];
tippyHover(ref, function() {
// use id or data attribute instead here
let href = ref.getAttribute('data-footnote-href') || ref.getAttribute('href');
try { href = new URL(href).hash; } catch {}
const id = href.replace(/^#\/?/, "");
const note = window.document.getElementById(id);
if (note) {
return note.innerHTML;
} else {
return "";
}
});
}
const xrefs = window.document.querySelectorAll('a.quarto-xref');
const processXRef = (id, note) => {
// Strip column container classes
const stripColumnClz = (el) => {
el.classList.remove("page-full", "page-columns");
if (el.children) {
for (const child of el.children) {
stripColumnClz(child);
}
}
}
stripColumnClz(note)
if (id === null || id.startsWith('sec-')) {
// Special case sections, only their first couple elements
const container = document.createElement("div");
if (note.children && note.children.length > 2) {
container.appendChild(note.children[0].cloneNode(true));
for (let i = 1; i < note.children.length; i++) {
const child = note.children[i];
if (child.tagName === "P" && child.innerText === "") {
continue;
} else {
container.appendChild(child.cloneNode(true));
break;
}
}
if (window.Quarto?.typesetMath) {
window.Quarto.typesetMath(container);
}
return container.innerHTML
} else {
if (window.Quarto?.typesetMath) {
window.Quarto.typesetMath(note);
}
return note.innerHTML;
}
} else {
// Remove any anchor links if they are present
const anchorLink = note.querySelector('a.anchorjs-link');
if (anchorLink) {
anchorLink.remove();
}
if (window.Quarto?.typesetMath) {
window.Quarto.typesetMath(note);
}
// TODO in 1.5, we should make sure this works without a callout special case
if (note.classList.contains("callout")) {
return note.outerHTML;
} else {
return note.innerHTML;
}
}
}
for (var i=0; i<xrefs.length; i++) {
const xref = xrefs[i];
tippyHover(xref, undefined, function(instance) {
instance.disable();
let url = xref.getAttribute('href');
let hash = undefined;
if (url.startsWith('#')) {
hash = url;
} else {
try { hash = new URL(url).hash; } catch {}
}
if (hash) {
const id = hash.replace(/^#\/?/, "");
const note = window.document.getElementById(id);
if (note !== null) {
try {
const html = processXRef(id, note.cloneNode(true));
instance.setContent(html);
} finally {
instance.enable();
instance.show();
}
} else {
// See if we can fetch this
fetch(url.split('#')[0])
.then(res => res.text())
.then(html => {
const parser = new DOMParser();
const htmlDoc = parser.parseFromString(html, "text/html");
const note = htmlDoc.getElementById(id);
if (note !== null) {
const html = processXRef(id, note);
instance.setContent(html);
}
}).finally(() => {
instance.enable();
instance.show();
});
}
} else {
// See if we can fetch a full url (with no hash to target)
// This is a special case and we should probably do some content thinning / targeting
fetch(url)
.then(res => res.text())
.then(html => {
const parser = new DOMParser();
const htmlDoc = parser.parseFromString(html, "text/html");
const note = htmlDoc.querySelector('main.content');
if (note !== null) {
// This should only happen for chapter cross references
// (since there is no id in the URL)
// remove the first header
if (note.children.length > 0 && note.children[0].tagName === "HEADER") {
note.children[0].remove();
}
const html = processXRef(null, note);
instance.setContent(html);
}
}).finally(() => {
instance.enable();
instance.show();
});
}
}, function(instance) {
});
}
let selectedAnnoteEl;
const selectorForAnnotation = ( cell, annotation) => {
let cellAttr = 'data-code-cell="' + cell + '"';
let lineAttr = 'data-code-annotation="' + annotation + '"';
const selector = 'span[' + cellAttr + '][' + lineAttr + ']';
return selector;
}
const selectCodeLines = (annoteEl) => {
const doc = window.document;
const targetCell = annoteEl.getAttribute("data-target-cell");
const targetAnnotation = annoteEl.getAttribute("data-target-annotation");
const annoteSpan = window.document.querySelector(selectorForAnnotation(targetCell, targetAnnotation));
const lines = annoteSpan.getAttribute("data-code-lines").split(",");
const lineIds = lines.map((line) => {
return targetCell + "-" + line;
})
let top = null;
let height = null;
let parent = null;
if (lineIds.length > 0) {
//compute the position of the single el (top and bottom and make a div)
const el = window.document.getElementById(lineIds[0]);
top = el.offsetTop;
height = el.offsetHeight;
parent = el.parentElement.parentElement;
if (lineIds.length > 1) {
const lastEl = window.document.getElementById(lineIds[lineIds.length - 1]);
const bottom = lastEl.offsetTop + lastEl.offsetHeight;
height = bottom - top;
}
if (top !== null && height !== null && parent !== null) {
// cook up a div (if necessary) and position it
let div = window.document.getElementById("code-annotation-line-highlight");
if (div === null) {
div = window.document.createElement("div");
div.setAttribute("id", "code-annotation-line-highlight");
div.style.position = 'absolute';
parent.appendChild(div);
}
div.style.top = top - 2 + "px";
div.style.height = height + 4 + "px";
div.style.left = 0;
let gutterDiv = window.document.getElementById("code-annotation-line-highlight-gutter");
if (gutterDiv === null) {
gutterDiv = window.document.createElement("div");
gutterDiv.setAttribute("id", "code-annotation-line-highlight-gutter");
gutterDiv.style.position = 'absolute';
const codeCell = window.document.getElementById(targetCell);
const gutter = codeCell.querySelector('.code-annotation-gutter');
gutter.appendChild(gutterDiv);
}
gutterDiv.style.top = top - 2 + "px";
gutterDiv.style.height = height + 4 + "px";
}
selectedAnnoteEl = annoteEl;
}
};
const unselectCodeLines = () => {
const elementsIds = ["code-annotation-line-highlight", "code-annotation-line-highlight-gutter"];
elementsIds.forEach((elId) => {
const div = window.document.getElementById(elId);
if (div) {
div.remove();
}
});
selectedAnnoteEl = undefined;
};
// Handle positioning of the toggle
window.addEventListener(
"resize",
throttle(() => {
elRect = undefined;
if (selectedAnnoteEl) {
selectCodeLines(selectedAnnoteEl);
}
}, 10)
);
function throttle(fn, ms) {
let throttle = false;
let timer;
return (...args) => {
if(!throttle) { // first call gets through
fn.apply(this, args);
throttle = true;
} else { // all the others get throttled
if(timer) clearTimeout(timer); // cancel #2
timer = setTimeout(() => {
fn.apply(this, args);
timer = throttle = false;
}, ms);
}
};
}
// Attach click handler to the DT
const annoteDls = window.document.querySelectorAll('dt[data-target-cell]');
for (const annoteDlNode of annoteDls) {
annoteDlNode.addEventListener('click', (event) => {
const clickedEl = event.target;
if (clickedEl !== selectedAnnoteEl) {
unselectCodeLines();
const activeEl = window.document.querySelector('dt[data-target-cell].code-annotation-active');
if (activeEl) {
activeEl.classList.remove('code-annotation-active');
}
selectCodeLines(clickedEl);
clickedEl.classList.add('code-annotation-active');
} else {
// Unselect the line
unselectCodeLines();
clickedEl.classList.remove('code-annotation-active');
}
});
}
const findCites = (el) => {
const parentEl = el.parentElement;
if (parentEl) {
const cites = parentEl.dataset.cites;
if (cites) {
return {
el,
cites: cites.split(' ')
};
} else {
return findCites(el.parentElement)
}
} else {
return undefined;
}
};
var bibliorefs = window.document.querySelectorAll('a[role="doc-biblioref"]');
for (var i=0; i<bibliorefs.length; i++) {
const ref = bibliorefs[i];
const citeInfo = findCites(ref);
if (citeInfo) {
tippyHover(citeInfo.el, function() {
var popup = window.document.createElement('div');
citeInfo.cites.forEach(function(cite) {
var citeDiv = window.document.createElement('div');
citeDiv.classList.add('hanging-indent');
citeDiv.classList.add('csl-entry');
var biblioDiv = window.document.getElementById('ref-' + cite);
if (biblioDiv) {
citeDiv.innerHTML = biblioDiv.innerHTML;
}
popup.appendChild(citeDiv);
});
return popup.innerHTML;
});
}
}
});
</script>
<script src="https://utteranc.es/client.js" repo="kidwellj/hacking_religion_textbook" issue-term="pathname" theme="github-light" crossorigin="anonymous" async="">
</script>
<nav class="page-navigation">
<div class="nav-page nav-page-previous">
</div>
<div class="nav-page nav-page-next">
<a href="./chapter_1.html" class="pagination-link" aria-label="Set up local workspace:">
<span class="nav-page-text"><span class="chapter-number">1</span>&nbsp; <span class="chapter-title">Set up local workspace:</span></span> <i class="bi bi-arrow-right-short"></i>
</a>
</div>
</nav>
</div> <!-- /content -->
</body></html>