<navclass="quarto-page-breadcrumbs"aria-label="breadcrumb"><olclass="breadcrumb"><liclass="breadcrumb-item"><ahref="./chapter_1.html"><spanclass="chapter-number">1</span> <spanclass="chapter-title">Set up local workspace:</span></a></li></ol></nav>
<spanclass="menu-text"><spanclass="chapter-number">2</span> <spanclass="chapter-title">Different ways to measure religion using data science</span></span></a>
<spanclass="menu-text"><spanclass="chapter-number">3</span> <spanclass="chapter-title">Mapping churches: geospatial data science</span></span></a>
<spanclass="menu-text"><spanclass="chapter-number">4</span> <spanclass="chapter-title">Data scraping, corpus analysis and wordclouds</span></span></a>
<li><ahref="#introducing-the-2021-uk-census"id="toc-introducing-the-2021-uk-census"class="nav-link active"data-scroll-target="#introducing-the-2021-uk-census"><spanclass="header-section-number">2</span> Introducing the 2021 UK Census</a></li>
<li><ahref="#getting-started-with-uk-census-data"id="toc-getting-started-with-uk-census-data"class="nav-link"data-scroll-target="#getting-started-with-uk-census-data"><spanclass="header-section-number">3</span> Getting started with UK Census data</a></li>
<li><ahref="#parsing-and-exploring-your-data"id="toc-parsing-and-exploring-your-data"class="nav-link"data-scroll-target="#parsing-and-exploring-your-data"><spanclass="header-section-number">5</span> Parsing and Exploring your data</a></li>
<li><ahref="#making-your-first-data-visulation-the-humble-bar-chart"id="toc-making-your-first-data-visulation-the-humble-bar-chart"class="nav-link"data-scroll-target="#making-your-first-data-visulation-the-humble-bar-chart"><spanclass="header-section-number">6</span> Making your first data visulation: the humble bar chart</a>
<li><ahref="#telling-the-truth-in-data-science-is-your-chart-accurate"id="toc-telling-the-truth-in-data-science-is-your-chart-accurate"class="nav-link"data-scroll-target="#telling-the-truth-in-data-science-is-your-chart-accurate"><spanclass="header-section-number">7</span> Telling the truth in data science: Is your chart accurate?</a></li>
<p>In this chapter we’re 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 you’ll learn to work with over the course of this chapter.</p>
<p>We’ll 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 hadn’t 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 you’re running the code as we go along, you’ll 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>
<divclass="sourceCode cell-code"id="cb1"><preclass="sourceCode r code-with-copy"><codeclass="sourceCode r"><spanid="cb1-1"><ahref="#cb1-1"aria-hidden="true"tabindex="-1"></a><spanclass="fu">setwd</span>(<spanclass="st">"/Users/kidwellj/gits/hacking_religion_textbook/hacking_religion"</span>)</span>
<spanid="cb1-4"><ahref="#cb1-4"aria-hidden="true"tabindex="-1"></a>here<spanclass="sc">::</span><spanclass="fu">i_am</span>(<spanclass="st">"chapter_1.qmd"</span>)</span></code><buttontitle="Copy to Clipboard"class="code-copy-button"><iclass="bi"></i></button></pre></div>
<spanid="cb3-9"><ahref="#cb3-9"aria-hidden="true"tabindex="-1"></a>}</span></code><buttontitle="Copy to Clipboard"class="code-copy-button"><iclass="bi"></i></button></pre></div>
<p>For our first exercise in this book, we’re going to work with a census dataset. As you’ll see by contrast in chapter 2, census data is intended to represent as fully as possible the demographic features of a specific community, in this case, the United Kingdom. We might assume that a large-scale survey given to 1000 or more respondents and distributed appropriately across a variety of demographics will approximate the results of a census, but there’s really no substitite for a survey which has been given to (nearly) the entire population. This also allows us to compare a number of different subsets, as we’ll explore further below. The big question that we’re confronting in this chapter is how best to represent religious belonging and participation at such a large scale, and to flag up some of the hidden limitations in this seemingly comprehensive dataset.</p>
<p>Let’s start by importing some data into R. Because R is what is called an object-oriented programming language, we’ll always take our information and give it a home inside a named object. There are many different kinds of objects, which you can specify, but usually R will assign a type that seems to fit best, often a table of data which looks a bit like a spreadsheet which is called a <code>dataframe</code>.</p>
<divclass="page-columns page-full"><p></p><divclass="no-row-height column-margin column-container"><spanclass="margin-aside">If you’d like to explore this all in a bit more depth, you can find a very helpful summary in R for Data Science, chapter 8, <ahref="https://r4ds.hadley.nz/data-import#reading-data-from-a-file">“data import”</a>.</span></div></div>
<p>In the example below, we’re going to begin by reading in data from a comma separated value file (“csv”) which has rows of information on separate lines in a text file with each column separated by a comma. This is one of the standard plain text file formats. R has a function you can use to import this efficiently called <code>read.csv</code>. Each line of code in R usually starts with the object, and then follows with instructions on what we’re going to put inside it, where that comes from, and how to format it:</p>
<divclass="cell">
<divclass="sourceCode cell-code"id="cb4"><preclass="sourceCode r code-with-copy"><codeclass="sourceCode r"><spanid="cb4-1"><ahref="#cb4-1"aria-hidden="true"tabindex="-1"></a>uk_census_2021_religion <spanclass="ot"><-</span><spanclass="fu">read.csv</span>(<spanclass="fu">here</span>(<spanclass="st">"example_data"</span>, <spanclass="st">"census2021-ts030-rgn.csv"</span>)) </span></code><buttontitle="Copy to Clipboard"class="code-copy-button"><iclass="bi"></i></button></pre></div>
<divclass="sourceCode cell-code"id="cb5"><preclass="sourceCode r code-with-copy"><codeclass="sourceCode r"><spanid="cb5-1"><ahref="#cb5-1"aria-hidden="true"tabindex="-1"></a><spanclass="fu">head</span>(uk_census_2021_religion)</span></code><buttontitle="Copy to Clipboard"class="code-copy-button"><iclass="bi"></i></button></pre></div>
<divclass="sourceCode cell-code"id="cb7"><preclass="sourceCode r code-with-copy"><codeclass="sourceCode r"><spanid="cb7-1"><ahref="#cb7-1"aria-hidden="true"tabindex="-1"></a>knitr<spanclass="sc">::</span><spanclass="fu">kable</span>(<spanclass="fu">head</span>(uk_census_2021_religion))</span></code><buttontitle="Copy to Clipboard"class="code-copy-button"><iclass="bi"></i></button></pre></div>
<p>You can see how I’ve nested the previous command inside the <code>kable</code> command. For reference, in some cases when you’re 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 we’ve 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>
<divclass="sourceCode cell-code"id="cb8"><preclass="sourceCode r code-with-copy"><codeclass="sourceCode r"><spanid="cb8-1"><ahref="#cb8-1"aria-hidden="true"tabindex="-1"></a>knitr<spanclass="sc">::</span><spanclass="fu">kable</span>(<spanclass="fu">tail</span>(uk_census_2021_religion))</span></code><buttontitle="Copy to Clipboard"class="code-copy-button"><iclass="bi"></i></button></pre></div>
<p>The first thing you’re going to want to do is to take a smaller subset of a large data set, either by filtering out certain columns or rows. Let’s say we want to just work with the data from the West Midlands and we’d 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>
<p>In the line above, you’ll see that we’ve 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 you’ll 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>It’s also worth noting that there are only a few rules for naming objects (you can’t have spaces, for one thing), so you’ll 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 we’ll use select in a different way to narrow our data to specific <em>columns</em> that are needed (no totals!).</p>
<divclass="page-columns page-full"><p></p><divclass="no-row-height column-margin column-container"><spanclass="margin-aside">Some readers will want to pause here and check out Hadley Wickham’s “R For Data Science” book, in the section, <ahref="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, we’re going to move on to producing some snappy looking charts for this data.</p>
<divclass="sourceCode cell-code"id="cb10"><preclass="sourceCode r code-with-copy"><codeclass="sourceCode r"><spanid="cb10-1"><ahref="#cb10-1"aria-hidden="true"tabindex="-1"></a>uk_census_2021_religion_wmids <spanclass="ot"><-</span> uk_census_2021_religion_wmids <spanclass="sc">%>%</span><spanclass="fu">select</span>(no_religion<spanclass="sc">:</span>no_response)</span>
<spanid="cb10-2"><ahref="#cb10-2"aria-hidden="true"tabindex="-1"></a>uk_census_2021_religion_wmids <spanclass="ot"><-</span><spanclass="fu">gather</span>(uk_census_2021_religion_wmids)</span></code><buttontitle="Copy to Clipboard"class="code-copy-button"><iclass="bi"></i></button></pre></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 (and extremely popular) library called ggplot which aims to streamline the coding you need to make a chart:</p>
<p>Here’s the code you can use to create a new data object which contains the information necessary for our chart. I’ve just used the generic name “df” because we won’t hold on to this chart. You’ll also see that I’ve 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>
<divclass="sourceCode cell-code"id="cb11"><preclass="sourceCode r code-with-copy"><codeclass="sourceCode r"><spanid="cb11-1"><ahref="#cb11-1"aria-hidden="true"tabindex="-1"></a>df <spanclass="ot"><-</span> uk_census_2021_religion_wmids[<spanclass="fu">order</span>(uk_census_2021_religion_wmids<spanclass="sc">$</span>value,<spanclass="at">decreasing =</span><spanclass="cn">TRUE</span>),]</span>
<spanid="cb11-2"><ahref="#cb11-2"aria-hidden="true"tabindex="-1"></a><spanclass="fu">barplot</span>(<spanclass="at">height=</span>df<spanclass="sc">$</span>value, <spanclass="at">names=</span>df<spanclass="sc">$</span>key)</span></code><buttontitle="Copy to Clipboard"class="code-copy-button"><iclass="bi"></i></button></pre></div>
<p>This initial chart doesn’t include a “totals” column, as it isn’t in the data and these plotting tools simply represent whatever data you put into them. It’s nice to have a list of sums for each column, and this is pretty easy to do in R. As you’ll see below, we are going to take the original table, and overwrite it with a new column added:</p>
<spandata-code-cell="annotated-cell-12"data-code-lines="1"data-code-annotation="1">First, remove the column with region names and the totals for the regions as we want just integer data.</span>
<spandata-code-cell="annotated-cell-12"data-code-lines="3"data-code-annotation="2">Second calculate the totals. In this example we use the tidyverse library <code>dplyr()</code>, but you can also do this using base R with <code>colsums()</code> like this: <code>uk_census_2021_religion_totals <- colSums(uk_census_2021_religion_totals, na.rm = TRUE)</code>. The downside with base R is that you’ll also need to convert the result into a dataframe for <code>ggplot</code> like this: <code>uk_census_2021_religion_totals <- as.data.frame(uk_census_2021_religion_totals)</code></span>
<spandata-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>
<p>You might notice that these two dataframes give us somewhat different results. But with data science, it’s 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>
<divclass="sourceCode cell-code"id="cb12"><preclass="sourceCode r code-with-copy"><codeclass="sourceCode r"><spanid="cb12-1"><ahref="#cb12-1"aria-hidden="true"tabindex="-1"></a>uk_census_2021_religion_merged <spanclass="ot"><-</span><spanclass="fu">rbind</span>(uk_census_2021_religion_totals, uk_census_2021_religion_wmids)</span></code><buttontitle="Copy to Clipboard"class="code-copy-button"><iclass="bi"></i></button></pre></div>
<p>Do you notice there’s 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>
<spanid="cb13-3"><ahref="#cb13-3"aria-hidden="true"tabindex="-1"></a>uk_census_2021_religion_merged <spanclass="ot"><-</span><spanclass="fu">rbind</span>(uk_census_2021_religion_totals, uk_census_2021_religion_wmids)</span></code><buttontitle="Copy to Clipboard"class="code-copy-button"><iclass="bi"></i></button></pre></div>
<p>If you’re looking closely, you will notice that I’ve added two elements to our previous ggplot. I’ve asked ggplot to fill in the columns with reference to the <code>dataset</code> column we’ve just created. Then I’ve also asked ggplot to alter the <code>position="dodge"</code> which places bars side by side rather than stacked on top of one another. You can give it a try without this instruction to see how this works. We will use stacked bars in a later chapter, so remember this feature.</p>
<p>If you inspect our chart, you can see that we’re getting closer, but it’s not really that helpful to compare the totals. What we need to do is get percentages that can be compared side by side. This is easy to do using another <code>dplyr</code> feature <code>mutate</code>:</p>
<divclass="page-columns page-full"><p></p><divclass="no-row-height column-margin column-container"><spanclass="margin-aside">You can find a helpful write-up about dplyr by Antoine Soetewey at, <ahref="https://statsandr.com/blog/introduction-to-data-manipulation-in-r-with-dplyr/">“Stats and R”</a>.</span></div></div>
<divclass="page-columns page-full"><p></p><divclass="no-row-height column-margin column-container"><spanclass="margin-aside">It’s worth noting that an alternative approach is to leave the numbers intact and simply label them differently so they render as percentages on your charts. You can do this with the `scales() library and the label_percent() function. The downside of this approach is that it won’t transfer to tables if you make them.</span></div></div>
<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 we’ve used here can be applied to draw in more data. You could, for example, compare census data from different years, e.g. 2001 2011 and 2021, as we’ll 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>We’ll draw this data into comparison with later sets in the next chapter. But the one glaring issue which remains for our chart is that it’s 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 works by stacking additional elements on to your original plot using <code>+</code>. So, for example, let’s 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>We might also want to add a border to our bars to make them more visually striking (notice the addition of <code>color</code> to the geom_bar below. I’ve also added <code>reorder()</code> to the x value to sort descending from the largest to smallest.</p>
<divclass="page-columns page-full"><p></p><divclass="no-row-height column-margin column-container"><spanclass="margin-aside">You can find more information about reordering ggplots on the <ahref="https://r-graph-gallery.com/267-reorder-a-variable-in-ggplot2.html">R Graph gallery</a>.</span></div></div>
<p>We can fine tune a few other visual features here as well, like adding a title with <code>ggtitle</code> and some prettier fonts with <code>theme_ipsum()</code> (which requires the <code>hrbrthemes()</code> library). We can also remove the x and y axis labels (not the data labels, which are rather important).</p>
<p>It’s also a bit hard to read our Y-axis labels with everything getting cramped down there, so let’s rotate that text to 180 degrees so those labels are clear:</p>
<divclass="cell">
<divclass="sourceCode cell-code"id="cb18"><preclass="sourceCode r code-with-copy"><codeclass="sourceCode r"><spanid="cb18-1"><ahref="#cb18-1"aria-hidden="true"tabindex="-1"></a><spanclass="fu">ggplot</span>(uk_census_2021_religion_merged, <spanclass="fu">aes</span>(<spanclass="at">fill=</span><spanclass="fu">fct_reorder</span>(dataset, value), <spanclass="at">x=</span><spanclass="fu">reorder</span>(key,<spanclass="sc">-</span>value),value, <spanclass="at">y=</span>perc)) <spanclass="sc">+</span><spanclass="fu">geom_bar</span>(<spanclass="at">position=</span><spanclass="st">"dodge"</span>, <spanclass="at">stat =</span><spanclass="st">"identity"</span>, <spanclass="at">colour =</span><spanclass="st">"black"</span>) <spanclass="sc">+</span><spanclass="fu">scale_fill_brewer</span>(<spanclass="at">palette =</span><spanclass="st">"Set1"</span>) <spanclass="sc">+</span><spanclass="fu">ggtitle</span>(<spanclass="st">"Religious Affiliation in the UK: 2021"</span>) <spanclass="sc">+</span><spanclass="fu">xlab</span>(<spanclass="st">""</span>) <spanclass="sc">+</span><spanclass="fu">ylab</span>(<spanclass="st">""</span>) <spanclass="sc">+</span><spanclass="fu">theme</span>(<spanclass="at">axis.text.x =</span><spanclass="fu">element_text</span>(<spanclass="at">angle =</span><spanclass="dv">90</span>, <spanclass="at">vjust =</span><spanclass="fl">0.5</span>, <spanclass="at">hjust=</span><spanclass="dv">1</span>))</span></code><buttontitle="Copy to Clipboard"class="code-copy-button"><iclass="bi"></i></button></pre></div>
<p>If you’ve been following along up until this point, you’ll 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 I’d 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. 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. It’s 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>It’s 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 don’t know. It’s 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 they’d 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 we’ll explore a bit more in the next chapter.</p>
<p>Given this challenge, some survey instruments randomise the order of questions. This hasn’t 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 can’t 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, it’s 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, it’s 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 doesn’t 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 don’t 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>
<divclass="sourceCode cell-code"id="cb19"><preclass="sourceCode r code-with-copy"><codeclass="sourceCode r"><spanid="cb19-1"><ahref="#cb19-1"aria-hidden="true"tabindex="-1"></a><spanclass="fu">ggplot</span>(uk_census_2021_religion_merged, <spanclass="fu">aes</span>(<spanclass="at">fill=</span><spanclass="fu">fct_reorder</span>(dataset, value), <spanclass="at">x=</span><spanclass="fu">reorder</span>(key,<spanclass="sc">-</span>value),value, <spanclass="at">y=</span>perc)) <spanclass="sc">+</span><spanclass="fu">geom_bar</span>(<spanclass="at">position=</span><spanclass="st">"dodge"</span>, <spanclass="at">stat =</span><spanclass="st">"identity"</span>, <spanclass="at">colour =</span><spanclass="st">"black"</span>) <spanclass="sc">+</span><spanclass="fu">scale_fill_brewer</span>(<spanclass="at">palette =</span><spanclass="st">"Set1"</span>) <spanclass="sc">+</span><spanclass="fu">ggtitle</span>(<spanclass="st">"Religious Affiliation in the 2021 Census of England and Wales"</span>) <spanclass="sc">+</span><spanclass="fu">xlab</span>(<spanclass="st">""</span>) <spanclass="sc">+</span><spanclass="fu">ylab</span>(<spanclass="st">""</span>) <spanclass="sc">+</span><spanclass="fu">theme</span>(<spanclass="at">axis.text.x =</span><spanclass="fu">element_text</span>(<spanclass="at">angle =</span><spanclass="dv">90</span>, <spanclass="at">vjust =</span><spanclass="fl">0.5</span>, <spanclass="at">hjust=</span><spanclass="dv">1</span>))</span></code><buttontitle="Copy to Clipboard"class="code-copy-button"><iclass="bi"></i></button></pre></div>
<p>One element of R data analysis of census datasets that can get really interesting is working with multiple variables. Above we’ve looked at the breakdown of religious affiliation across the whole of England and Wales (Scotland operates an independent census so we haven’t included it here) and by placing this data alongside a specific region, we’ve 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. Let’s have a look at the way that religion in England and Wales breaks down by ethnicity.</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. It’s worth noting that if you’re not in the UK, there are similar options for other countries. Nearly every R textbook I’ve ever seen works with USA census data (which is part of the reason I’ve taken the opportunity to work with a different national census dataset here in this book), so you’ll 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 <ahref="https://github.com/kidwellj/hacking_religion_cookbook/blob/main/nomis.R">companion cookbook repository</a>. For now, we’ll provide some data extracts for you to use.</p>
<p>I’m 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, you’re 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, I’ve 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 we’d 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>
<aclass="code-annotation-anchor"data-target-cell="annotated-cell-23"data-target-annotation="3"onclick="event.preventDefault();">3</a><spanid="annotated-cell-23-5"class="code-annotation-target"><ahref="#annotated-cell-23-5"aria-hidden="true"tabindex="-1"></a>uk_census_2021_religion_ethnicity <spanclass="ot"><-</span><spanclass="fu">filter</span>(uk_census_2021_religion_ethnicity, C2021_ETH_8_NAME <spanclass="sc">!=</span><spanclass="st">"White: English, Welsh, Scottish, Northern Irish or British"</span><spanclass="sc">&</span> C2021_ETH_8_NAME <spanclass="sc">!=</span><spanclass="st">"White: Irish"</span><spanclass="sc">&</span> C2021_ETH_8_NAME <spanclass="sc">!=</span><spanclass="st">"White: Gypsy or Irish Traveller, Roma or Other White"</span>)</span>
<spanid="annotated-cell-23-10"><ahref="#annotated-cell-23-10"aria-hidden="true"tabindex="-1"></a><spanclass="fu">ggtitle</span>(<spanclass="st">"Religious Affiliation in the 2021 Census of England and Wales"</span>) <spanclass="sc">+</span></span>
<spandata-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>
<spandata-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>
<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 <ahref="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>
<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, we’ve hit another scenario here, the difference between the “White” subcategory and all the others is large enough that those other four categories aren’t 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 didn’t represent the same amount of value, e.g. 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. That’s 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>
<aclass="code-annotation-anchor"data-target-cell="annotated-cell-24"data-target-annotation="3"onclick="event.preventDefault();">3</a><spanid="annotated-cell-24-5"class="code-annotation-target"><ahref="#annotated-cell-24-5"aria-hidden="true"tabindex="-1"></a><spanclass="fu">ggplot</span>(uk_census_2021_religion_ethnicity_nonwhite, <spanclass="fu">aes</span>(<spanclass="at">fill=</span>C2021_ETH_8_NAME, <spanclass="at">x=</span>C2021_RELIGION_10_NAME, <spanclass="at">y=</span>OBS_VALUE)) <spanclass="sc">+</span><spanclass="fu">geom_bar</span>(<spanclass="at">position=</span><spanclass="st">"dodge"</span>, <spanclass="at">stat =</span><spanclass="st">"identity"</span>, <spanclass="at">colour =</span><spanclass="st">"black"</span>) <spanclass="sc">+</span><spanclass="fu">scale_fill_brewer</span>(<spanclass="at">palette =</span><spanclass="st">"Set1"</span>) <spanclass="sc">+</span><spanclass="fu">ggtitle</span>(<spanclass="st">"Religious Affiliation in the 2021 Census of England and Wales"</span>) <spanclass="sc">+</span><spanclass="fu">xlab</span>(<spanclass="st">""</span>) <spanclass="sc">+</span><spanclass="fu">ylab</span>(<spanclass="st">""</span>) <spanclass="sc">+</span><spanclass="fu">theme</span>(<spanclass="at">axis.text.x =</span><spanclass="fu">element_text</span>(<spanclass="at">angle =</span><spanclass="dv">90</span>, <spanclass="at">vjust =</span><spanclass="fl">0.5</span>, <spanclass="at">hjust=</span><spanclass="dv">1</span>))</span><divclass="code-annotation-gutter-bg"></div><divclass="code-annotation-gutter"></div></code><buttontitle="Copy to Clipboard"class="code-copy-button"><iclass="bi"></i></button></pre></div>
<spandata-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>
<spandata-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>
<p>As you’ll notice, this is a bit better, but this still doesn’t quite render with as much visual clarity and communication as I’d 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. 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>
<spanid="cb21-8"><ahref="#cb21-8"aria-hidden="true"tabindex="-1"></a><spanclass="fu">ggtitle</span>(<spanclass="st">"Religious Affiliation in the 2021 Census of England and Wales"</span>) <spanclass="sc">+</span></span>
<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 won’t 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, you’ll want to observe that we’ve 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>
<divclass="cell">
<divclass="sourceCode cell-code"id="cb22"><preclass="sourceCode r code-with-copy"><codeclass="sourceCode r"><spanid="cb22-1"><ahref="#cb22-1"aria-hidden="true"tabindex="-1"></a><spanclass="fu">ggplot</span>(uk_census_2021_religion_ethnicity_nonwhite, <spanclass="fu">aes</span>(<spanclass="at">x=</span>C2021_RELIGION_10_NAME, <spanclass="at">y=</span>OBS_VALUE)) <spanclass="sc">+</span></span>
<spanid="cb22-4"><ahref="#cb22-4"aria-hidden="true"tabindex="-1"></a><spanclass="fu">ggtitle</span>(<spanclass="st">"Religious Affiliation in the 2021 Census of England and Wales"</span>) <spanclass="sc">+</span><spanclass="fu">xlab</span>(<spanclass="st">""</span>) <spanclass="sc">+</span><spanclass="fu">ylab</span>(<spanclass="st">""</span>) <spanclass="sc">+</span></span>
<spanid="cb22-5"><ahref="#cb22-5"aria-hidden="true"tabindex="-1"></a><spanclass="fu">theme</span>(<spanclass="at">axis.text.x =</span><spanclass="fu">element_text</span>(<spanclass="at">angle =</span><spanclass="dv">90</span>, <spanclass="at">vjust =</span><spanclass="fl">0.5</span>, <spanclass="at">hjust=</span><spanclass="dv">1</span>))</span></code><buttontitle="Copy to Clipboard"class="code-copy-button"><iclass="bi"></i></button></pre></div>
<p>That’s a bit better! Now we have a much more accessible set of visual information which compares across categories and renders most of the information we’re trying to capture.</p>
<p>To take this chart just one step further, I’d like to take the faceted chart we’ve 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. We’ll draw on some techniques we’re already developed above using <code>rbind()</code> to connect up each of these charts (after we’ve 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 isn’t consistent from one census to the next and ggplot will struggle to chart things if the terms being used are exactly the same. We’ll 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>
<spandata-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>
<p>The <code>bind</code> tool we’re going to use is very picky and expects everything to match perfectly so that it doesn’t 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 you’ll face in working with multiple datasets in the same chart, so well worth noticing the extra necessary step here.</p>
<spandata-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 don’t lose track of the census it comes from when they’re all combined into a single table.</span>
<spandata-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>
<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, we’ll use the very handy tool <code>mutate</code> which is a bit like a “find and replace text” tool in R:</p>
<divclass="sourceCode cell-code"id="cb24"><preclass="sourceCode r code-with-copy"><codeclass="sourceCode r"><spanid="cb24-1"><ahref="#cb24-1"aria-hidden="true"tabindex="-1"></a><spanclass="co"># Next we need to change the terms using mutate()</span></span>
<spanid="cb24-10"><ahref="#cb24-10"aria-hidden="true"tabindex="-1"></a><spanclass="at">pattern =</span><spanclass="st">"^Black or Black British: Total$"</span>, <spanclass="at">replacement =</span><spanclass="st">"Black"</span>)) <spanclass="sc">%>%</span></span>
<spanid="cb24-12"><ahref="#cb24-12"aria-hidden="true"tabindex="-1"></a><spanclass="at">pattern =</span><spanclass="st">"^Chinese or Other ethnic group: Total$"</span>, <spanclass="at">replacement =</span><spanclass="st">"Other"</span>))</span>
<spanid="cb24-32"><ahref="#cb24-32"aria-hidden="true"tabindex="-1"></a><spanclass="at">pattern =</span><spanclass="st">"^Asian, Asian British or Asian Welsh$"</span>, <spanclass="at">replacement =</span><spanclass="st">"Asian"</span>)) <spanclass="sc">%>%</span></span>
<spanid="cb24-34"><ahref="#cb24-34"aria-hidden="true"tabindex="-1"></a><spanclass="at">pattern =</span><spanclass="st">"^Black, Black British, Black Welsh, Caribbean or African$"</span>, <spanclass="at">replacement =</span><spanclass="st">"Black"</span>)) <spanclass="sc">%>%</span></span>
<p>Now that we have all the columns and data in formats which will match for merge, let’d 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>
<divclass="sourceCode cell-code"id="cb25"><preclass="sourceCode r code-with-copy"><codeclass="sourceCode r"><spanid="cb25-1"><ahref="#cb25-1"aria-hidden="true"tabindex="-1"></a>uk_census_merged_religion_ethnicity <spanclass="ot"><-</span><spanclass="fu">rbind</span>(uk_census_2021_religion_ethnicity, uk_census_2011_religion_ethnicity)</span>
<spanid="cb25-2"><ahref="#cb25-2"aria-hidden="true"tabindex="-1"></a>uk_census_merged_religion_ethnicity <spanclass="ot"><-</span><spanclass="fu">rbind</span>(uk_census_merged_religion_ethnicity, uk_census_2001_religion_ethnicity)</span></code><buttontitle="Copy to Clipboard"class="code-copy-button"><iclass="bi"></i></button></pre></div>
<divclass="sourceCode cell-code"id="cb26"><preclass="sourceCode r code-with-copy"><codeclass="sourceCode r"><spanid="cb26-1"><ahref="#cb26-1"aria-hidden="true"tabindex="-1"></a>uk_census_merged_religion_ethnicity_nonwhite <spanclass="ot"><-</span><spanclass="fu">filter</span>(uk_census_merged_religion_ethnicity, Ethnicity <spanclass="sc">!=</span><spanclass="st">"White"</span>)</span></code><buttontitle="Copy to Clipboard"class="code-copy-button"><iclass="bi"></i></button></pre></div>
<spanid="cb27-5"><ahref="#cb27-5"aria-hidden="true"tabindex="-1"></a><spanclass="fu">ggtitle</span>(<spanclass="st">"Religious Affiliation in the 2001-2021 Census of England and Wales"</span>) <spanclass="sc">+</span></span>
<p>We’re 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 isn’t 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>
<p>This chart shows an increase in almost every category for each decade, though it’s a bit hard to read in some cases. However, if we attend to our hacker principles, there’s 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>. It’s possbile that the numbers for each religion category may be going up, but population levels are also rising, and it’s possible here that the percentage share for a particular category may have gone up a bit less than population increase, e.g. 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. Let’s transform and visualise our data as percentages to see what kind of trends we can actually isolate:</p>
<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 I’ve added for this final plot, I’ve 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 we’re looking at trends here and not absolute values, having correspondence across scales isn’t important and this makes for something a bit more visually tidy. I’ve 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>
<spanid="cb30-6"><ahref="#cb30-6"aria-hidden="true"tabindex="-1"></a><spanclass="fu">ggtitle</span>(<spanclass="st">"Religious Affiliation in the 2001-2021 Censuses of England and Wales"</span>) <spanclass="sc">+</span></span>
<p>That’s a pretty good day’s work. We’ve covered bifactorial analysis of the census data, compared this across years, and checked in each case to be sure that we’re representing the data accurately in the various visual elements of our charts. For the next chapter, we’re 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>
// 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
<ahref="./chapter_2.html"class="pagination-link"aria-label="Different ways to measure religion using data science">
<spanclass="nav-page-text"><spanclass="chapter-number">2</span> <spanclass="chapter-title">Different ways to measure religion using data science</span></span><iclass="bi bi-arrow-right-short"></i>