From 08ca8db7918dc7cfcd73efa082d751a813ee7496 Mon Sep 17 00:00:00 2001 From: Jeremy Kidwell Date: Thu, 5 Oct 2023 14:29:31 +0100 Subject: [PATCH] updates to chapter 1 --- docs/chapter_1.html | 135 ++++++++++++++++++++------ docs/chapter_2.html | 6 +- docs/search.json | 44 +++++++-- hacking_religion/_book/chapter_1.html | 135 ++++++++++++++++++++------ hacking_religion/chapter_1.qmd | 99 ++++++++++++++++--- 5 files changed, 341 insertions(+), 78 deletions(-) diff --git a/docs/chapter_1.html b/docs/chapter_1.html index 5da2d00..edce4f2 100644 --- a/docs/chapter_1.html +++ b/docs/chapter_1.html @@ -210,12 +210,16 @@ div.csl-indent {

Table of contents

@@ -240,8 +244,8 @@ div.csl-indent { -
-

2.1 Your first project: building a pie chart

+
+

2.1 Your first project: the UK Census

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.

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, “data import”.

In the example below, we’re going to read 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 “read.csv”. 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:

@@ -272,8 +276,9 @@ i Use the conflicted package (<http://conflicted.r-lib.org/>) to force all
uk_census_2021_religion <- read.csv(here("example_data", "census2021-ts030-rgn.csv")) 
-
-

2.1.1 Examining data:

+
+
+

2.2 Examining data:

What’s in the table? You can take a quick look at either the top of the data frame, or the bottom using one of the following commands:

head(uk_census_2021_religion)
@@ -535,29 +540,27 @@ i Use the conflicted package (<http://conflicted.r-lib.org/>) to force all
-
-

2.1.2 Parsing and Exploring your data

+
+

2.3 Parsing and Exploring your data

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. Now let’s say we want to just work with the data from the West Midlands, and we’d like to omit some of the columns. We can choose a specific range of columns using select, like this:

You can use the filter command to do this. To give an example, filter can pick a single row in the following way:

-
uk_census_2021_religion_wmids <- uk_census_2021_religion %>% 
-  filter(geography=="West Midlands")  
+
uk_census_2021_religion_wmids <- uk_census_2021_religion %>% filter(geography=="West Midlands")  

Now we’ll use select in a different way to narrow our data to specific columns that are needed (no totals!).

Some readers will want to pause here and check out Hadley Wickham’s “R For Data Science” book, in the section, “Data visualisation” to get a fuller explanation of how to explore your data.

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.

-
-
-

2.2 Making your first chart

+
+

2.4 Making your first data visulation: the humble bar chart

We’ve got a nice lean set of data, so now it’s time to visualise this. We’ll start by making a pie chart:

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)

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:

-
-

2.2.0.1 Base R

+
+

2.4.1 Base R

df <- uk_census_2021_religion_wmids[order(uk_census_2021_religion_wmids$value,decreasing = TRUE),]
 barplot(height=df$value, names=df$key)
@@ -566,8 +569,8 @@ i Use the conflicted package (<http://conflicted.r-lib.org/>) to force all
-
-

2.2.0.2 GGPlot

+
+

2.4.2 GGPlot

ggplot(uk_census_2021_religion_wmids, aes(x = key, y = value)) +
   geom_bar(stat = "identity")
@@ -575,7 +578,7 @@ i Use the conflicted package (<http://conflicted.r-lib.org/>) to force all
2
-We’ll re-order the column by size. +We’ll re-order the column by size.
@@ -598,19 +601,19 @@ i Use the conflicted package (<http://conflicted.r-lib.org/>) to force all
1
-First, remove the column with region names and the totals for the regions as we want just integer data. +First, remove the column with region names and the totals for the regions as we want just integer data.
2
-Second calculate the totals. In this example we use the tidyverse library dplyr(), but you can also do this using base R with colsums() like this: uk_census_2021_religion_totals <- colSums(uk_census_2021_religion_totals, na.rm = TRUE). The downside with base R is that you’ll also need to convert the result into a dataframe for ggplot like this: uk_census_2021_religion_totals <- as.data.frame(uk_census_2021_religion_totals) +Second calculate the totals. In this example we use the tidyverse library dplyr(), but you can also do this using base R with colsums() like this: uk_census_2021_religion_totals <- colSums(uk_census_2021_religion_totals, na.rm = TRUE). The downside with base R is that you’ll also need to convert the result into a dataframe for ggplot like this: uk_census_2021_religion_totals <- as.data.frame(uk_census_2021_religion_totals)
3
-In order to visualise this data using ggplot, we need to shift this data from wide to long format. This is a quick job using gather() +In order to visualise this data using ggplot, we need to shift this data from wide to long format. This is a quick job using gather()
4
-Now plot it out and have a look! +Now plot it out and have a look!
@@ -648,14 +651,90 @@ i Use the conflicted package (<http://conflicted.r-lib.org/>) to force all

-

Now you can see a very rough comparison

-

Add time series data for 2001 and 2011 census, change to grouped bar plot:

-

https://r-graphics.org/recipe-bar-graph-grouped-bar#discussion-8

+

Now you can see a very rough comparison, which sets bars from the W Midlands data and overall 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. Our use of dplyr::mutate above can be repeated to add an infinite number of further series’ which can be plotted in bar groups.

+

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 ggplot really shines as a tool as you can add all sorts of things.

+

These are basically just added to our ggplot 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 scale using scale_fill_brewer. This uses a particular tool (and a personal favourite of mine) called colorbrewer. 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.

+
+
ggplot(uk_census_2021_religion_merged, aes(fill=dataset, x=key, y=perc)) + geom_bar(position="dodge", stat ="identity") + scale_fill_brewer(palette = "Set1")
+
+

+
+
+

We might also want to add a border to our bars to make them more visually striking (notice the addition of color to the geom_bar below. I’ve also added reorder() to the x value to sort descending from the largest to smallest.

+

You can find more information about reordering ggplots on the R Graph gallery.
+
+
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")
+
+

+
+
+

We can fine tune a few other visual features here as well, like adding a title with ggtitle and a them with some prettier fonts with theme_ipsum() (which requires the hrbrthemes() library). We can also remove the x and y axis labels (not the data labels, which are rather important).

+
+
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("")
+
+

+
+
+
+
+
+

2.5 Is your chart accurate? Telling the truth in data science

+

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. Is the title of this chart truthful and accurate? On one hand, it is a straight-forward reference to the nature of the question asked on the 2021 census survey instrument. 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. It’s 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. But 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, but the census hasn’t capture this so we simply don’t know. If a large portion of respondents in the”Christian” category were hovering between this and another response, again, they might shift their answers when responding on a different day, perhaps having just had a conversation with a friend which shifted their thinking. 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. For this reason, 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. 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”. The 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. Finally, it is interesting to wonder exactly what it means for a person when they tick a box like this. 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.

+

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, almost completely population level, sample so there is additional validity there. 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. We should also probably do something different with those non-responses:

+
+
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("")
+
+

+
+
+

Change orientation of X axis labels + theme(axis.text.x = element_text(angle = 90, vjust = 0.5, hjust=1))

+

Relabel fields Simplify y-axis labels Add percentage text to bars (or maybe save for next chapter?)

+
+
+

2.6 Multifactor Visualisation

+

One element of R data analysis 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), 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 quantative variable (also known as bivariate data) 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.

+
+
library(nomisr)
+
+# Process to explore nomis() data for specific datasets
+religion_search <- nomis_search(name = "*Religion*")
+religion_measures <- nomis_get_metadata("NM_529_1", "measures")
+tibble::glimpse(religion_measures)
+
+
Rows: 2
+Columns: 3
+$ id             <chr> "20100", "20301"
+$ label.en       <chr> "value", "percent"
+$ description.en <chr> "value", "percent"
+
+
religion_geography <- nomis_get_metadata("NM_529_1", "geography", "TYPE")
+
+# Get table of Census 2011 religion data from nomis
+z <- nomis_get_data(id = "NM_529_1", time = "latest", geography = "TYPE499", measures=c(20301))
+# Filter down to simplified dataset with England / Wales and percentages without totals
+uk_census_2011_religion <- filter(z, GEOGRAPHY_NAME=="England and Wales" & RURAL_URBAN_NAME=="Total" & C_RELPUK11_NAME != "All categories: Religion")
+# Drop unnecessary columns
+uk_census_2011_religion <- select(uk_census_2011_religion, C_RELPUK11_NAME, OBS_VALUE)
+# Plot results
+plot1 <- ggplot(uk_census_2011_religion, 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))
+ggsave(filename = "plot.png", plot = plot1)
+
+
Saving 7 x 5 in image
+
+
# grab data from nomis for 2011 census religion / ethnicity table
+z1 <- nomis_get_data(id = "NM_659_1", time = "latest", geography = "TYPE499", measures=c(20100))
+# select relevant columns
+uk_census_2011_religion_ethnicitity <- select(z1, GEOGRAPHY_NAME, C_RELPUK11_NAME, C_ETHPUK11_NAME, OBS_VALUE)
+# Filter down to simplified dataset with England / Wales and percentages without totals
+uk_census_2011_religion_ethnicitity <- filter(uk_census_2011_religion_ethnicitity, GEOGRAPHY_NAME=="England and Wales" & C_RELPUK11_NAME != "All categories: Religion" & C_ETHPUK11_NAME != "All categories: Ethnic group")
+# Simplify data to only include general totals and omit subcategories
+uk_census_2011_religion_ethnicitity <- uk_census_2011_religion_ethnicitity %>% filter(grepl('Total', C_ETHPUK11_NAME))
+
-

References

diff --git a/docs/search.json b/docs/search.json index 3528722..b164b46 100644 --- a/docs/search.json +++ b/docs/search.json @@ -56,18 +56,46 @@ "text": "References" }, { - "objectID": "chapter_1.html#your-first-project-building-a-pie-chart", - "href": "chapter_1.html#your-first-project-building-a-pie-chart", + "objectID": "chapter_1.html#your-first-project-the-uk-census", + "href": "chapter_1.html#your-first-project-the-uk-census", "title": "2  The 2021 UK Census", - "section": "2.1 Your first project: building a pie chart", - "text": "2.1 Your first project: building a pie chart\nLet’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.\nIf 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, “data import”.\nIn the example below, we’re going to read 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 “read.csv”. 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:\n\nsetwd(\"/Users/kidwellj/gits/hacking_religion_textbook/hacking_religion\")\nlibrary(here) # much better way to manage working paths in R across multiple instances\n\nhere() starts at /Users/kidwellj/gits/hacking_religion_textbook\n\nlibrary(tidyverse)\n\n-- Attaching core tidyverse packages ------------------------ tidyverse 2.0.0 --\nv dplyr 1.1.3 v readr 2.1.4\nv forcats 1.0.0 v stringr 1.5.0\nv ggplot2 3.4.3 v tibble 3.2.1\nv lubridate 1.9.3 v tidyr 1.3.0\nv purrr 1.0.2 \n\n\n-- Conflicts ------------------------------------------ tidyverse_conflicts() --\nx dplyr::filter() masks stats::filter()\nx dplyr::lag() masks stats::lag()\ni Use the conflicted package (<http://conflicted.r-lib.org/>) to force all conflicts to become errors\n\nhere::i_am(\"chapter_1.qmd\")\n\nhere() starts at /Users/kidwellj/gits/hacking_religion_textbook/hacking_religion\n\nuk_census_2021_religion <- read.csv(here(\"example_data\", \"census2021-ts030-rgn.csv\")) \n\n\n2.1.1 Examining data:\nWhat’s in the table? You can take a quick look at either the top of the data frame, or the bottom using one of the following commands:\n\nhead(uk_census_2021_religion)\n\n geography total no_religion christian buddhist hindu jewish\n1 North East 2647012 1058122 1343948 7026 10924 4389\n2 North West 7417397 2419624 3895779 23028 49749 33285\n3 Yorkshire and The Humber 5480774 2161185 2461519 15803 29243 9355\n4 East Midlands 4880054 1950354 2214151 14521 120345 4313\n5 West Midlands 5950756 1955003 2770559 18804 88116 4394\n6 East 6335072 2544509 2955071 26814 86631 42012\n muslim sikh other no_response\n1 72102 7206 9950 133345\n2 563105 11862 28103 392862\n3 442533 24034 23618 313484\n4 210766 53950 24813 286841\n5 569963 172398 31805 339714\n6 234744 24284 36380 384627\n\n\nThis is actually a fairly ugly table, so I’ll use an R tool called kable to give you prettier tables in the future, like this:\n\nknitr::kable(head(uk_census_2021_religion))\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\ngeography\ntotal\nno_religion\nchristian\nbuddhist\nhindu\njewish\nmuslim\nsikh\nother\nno_response\n\n\n\n\nNorth East\n2647012\n1058122\n1343948\n7026\n10924\n4389\n72102\n7206\n9950\n133345\n\n\nNorth West\n7417397\n2419624\n3895779\n23028\n49749\n33285\n563105\n11862\n28103\n392862\n\n\nYorkshire and The Humber\n5480774\n2161185\n2461519\n15803\n29243\n9355\n442533\n24034\n23618\n313484\n\n\nEast Midlands\n4880054\n1950354\n2214151\n14521\n120345\n4313\n210766\n53950\n24813\n286841\n\n\nWest Midlands\n5950756\n1955003\n2770559\n18804\n88116\n4394\n569963\n172398\n31805\n339714\n\n\nEast\n6335072\n2544509\n2955071\n26814\n86631\n42012\n234744\n24284\n36380\n384627\n\n\n\n\n\nYou can see how I’ve nested the previous command inside the kable 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. You can specify the library where the function is meant to come from by preceding it with :: as we’ve done knitr:: above. The same kind of output can be gotten using tail:\n\nknitr::kable(tail(uk_census_2021_religion))\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\ngeography\ntotal\nno_religion\nchristian\nbuddhist\nhindu\njewish\nmuslim\nsikh\nother\nno_response\n\n\n\n\n5\nWest Midlands\n5950756\n1955003\n2770559\n18804\n88116\n4394\n569963\n172398\n31805\n339714\n\n\n6\nEast\n6335072\n2544509\n2955071\n26814\n86631\n42012\n234744\n24284\n36380\n384627\n\n\n7\nLondon\n8799728\n2380404\n3577681\n77425\n453034\n145466\n1318754\n144543\n86759\n615662\n\n\n8\nSouth East\n9278068\n3733094\n4313319\n54433\n154748\n18682\n309067\n74348\n54098\n566279\n\n\n9\nSouth West\n5701186\n2513369\n2635872\n24579\n27746\n7387\n80152\n7465\n36884\n367732\n\n\n10\nWales\n3107494\n1446398\n1354773\n10075\n12242\n2044\n66947\n4048\n15926\n195041\n\n\n\n\n\n\n\n2.1.2 Parsing and Exploring your data\nThe 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. Now let’s say we want to just work with the data from the West Midlands, and we’d like to omit some of the columns. We can choose a specific range of columns using select, like this:\nYou can use the filter command to do this. To give an example, filter can pick a single row in the following way:\n\nuk_census_2021_religion_wmids <- uk_census_2021_religion %>% \n filter(geography==\"West Midlands\") \n\nNow we’ll use select in a different way to narrow our data to specific columns that are needed (no totals!).\nSome readers will want to pause here and check out Hadley Wickham’s “R For Data Science” book, in the section, “Data visualisation” to get a fuller explanation of how to explore your data.\nIn 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." + "section": "2.1 Your first project: the UK Census", + "text": "2.1 Your first project: the UK Census\nLet’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.\nIf 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, “data import”.\nIn the example below, we’re going to read 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 “read.csv”. 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:\n\nsetwd(\"/Users/kidwellj/gits/hacking_religion_textbook/hacking_religion\")\nlibrary(here) # much better way to manage working paths in R across multiple instances\n\nhere() starts at /Users/kidwellj/gits/hacking_religion_textbook\n\nlibrary(tidyverse)\n\n-- Attaching core tidyverse packages ------------------------ tidyverse 2.0.0 --\nv dplyr 1.1.3 v readr 2.1.4\nv forcats 1.0.0 v stringr 1.5.0\nv ggplot2 3.4.3 v tibble 3.2.1\nv lubridate 1.9.3 v tidyr 1.3.0\nv purrr 1.0.2 \n\n\n-- Conflicts ------------------------------------------ tidyverse_conflicts() --\nx dplyr::filter() masks stats::filter()\nx dplyr::lag() masks stats::lag()\ni Use the conflicted package (<http://conflicted.r-lib.org/>) to force all conflicts to become errors\n\nhere::i_am(\"chapter_1.qmd\")\n\nhere() starts at /Users/kidwellj/gits/hacking_religion_textbook/hacking_religion\n\nuk_census_2021_religion <- read.csv(here(\"example_data\", \"census2021-ts030-rgn.csv\"))" }, { - "objectID": "chapter_1.html#making-your-first-chart", - "href": "chapter_1.html#making-your-first-chart", + "objectID": "chapter_1.html#examining-data", + "href": "chapter_1.html#examining-data", "title": "2  The 2021 UK Census", - "section": "2.2 Making your first chart", - "text": "2.2 Making your first chart\nWe’ve got a nice lean set of data, so now it’s time to visualise this. We’ll start by making a pie chart:\n\nuk_census_2021_religion_wmids <- uk_census_2021_religion_wmids %>% select(no_religion:no_response)\nuk_census_2021_religion_wmids <- gather(uk_census_2021_religion_wmids)\n\nThere 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:\n\n2.2.0.1 Base R\n\ndf <- uk_census_2021_religion_wmids[order(uk_census_2021_religion_wmids$value,decreasing = TRUE),]\nbarplot(height=df$value, names=df$key)\n\n\n\n\n\n\n2.2.0.2 GGPlot\n\nggplot(uk_census_2021_religion_wmids, aes(x = key, y = value)) +\n geom_bar(stat = \"identity\")\n\n\n2\n\nWe’ll re-order the column by size.\n\n\n\n\n\n\n2ggplot(uk_census_2021_religion_wmids, aes(x= reorder(key,-value),value)) + geom_bar(stat =\"identity\")\n\n\n\n\nLet’s assume we’re working with a data set that doesn’t include a “totals” column and that we might want to get sums for each column. This is pretty easy to do in R:\n\n1uk_census_2021_religion_totals <- uk_census_2021_religion %>% select(no_religion:no_response)\nuk_census_2021_religion_totals <- uk_census_2021_religion_totals %>%\n2 summarise(across(everything(), ~ sum(., na.rm = TRUE)))\n3uk_census_2021_religion_totals <- gather(uk_census_2021_religion_totals)\n4ggplot(uk_census_2021_religion_totals, aes(x= reorder(key,-value),value)) + geom_bar(stat =\"identity\")\n\n\n1\n\nFirst, remove the column with region names and the totals for the regions as we want just integer data.\n\n2\n\nSecond calculate the totals. In this example we use the tidyverse library dplyr(), but you can also do this using base R with colsums() like this: uk_census_2021_religion_totals <- colSums(uk_census_2021_religion_totals, na.rm = TRUE). The downside with base R is that you’ll also need to convert the result into a dataframe for ggplot like this: uk_census_2021_religion_totals <- as.data.frame(uk_census_2021_religion_totals)\n\n3\n\nIn 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()\n\n4\n\nNow plot it out and have a look!\n\n\n\n\n\n\n\nYou might have noticed 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 bind() - which can be done by columns with cbind() and rows using rbind():\n\nuk_census_2021_religion_merged <- rbind(uk_census_2021_religion_totals, uk_census_2021_religion_wmids)\n\nDo 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! This isn’t too hard to do as we can simply create a new column for each with identifiable information before we bind them:\n\nuk_census_2021_religion_totals$dataset <- c(\"totals\")\nuk_census_2021_religion_wmids$dataset <- c(\"wmids\")\nuk_census_2021_religion_merged <- rbind(uk_census_2021_religion_totals, uk_census_2021_religion_wmids)\n\nNow we’re ready to plot out our data as a grouped barplot:\n\nggplot(uk_census_2021_religion_merged, aes(fill=dataset, x= reorder(key,-value), value)) + geom_bar(position=\"dodge\", stat =\"identity\")\n\n\n\n\nIf 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 dataset column we’ve just created. Then I’ve also asked ggplot to alter the position=\"dodge\" 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.\nIf 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 dplyr feature mutate:\n\nuk_census_2021_religion_totals <- uk_census_2021_religion_totals %>% \n dplyr::mutate(perc = scales::percent(value / sum(value), accuracy = 0.1, trim = FALSE))\nuk_census_2021_religion_wmids <- uk_census_2021_religion_wmids %>% \n dplyr::mutate(perc = scales::percent(value / sum(value), accuracy = 0.1, trim = FALSE))\nuk_census_2021_religion_merged <- rbind(uk_census_2021_religion_totals, uk_census_2021_religion_wmids)\nggplot(uk_census_2021_religion_merged, aes(fill=dataset, x=key, y=perc)) + geom_bar(position=\"dodge\", stat =\"identity\")\n\n\n\n\nNow you can see a very rough comparison\nAdd time series data for 2001 and 2011 census, change to grouped bar plot:\nhttps://r-graphics.org/recipe-bar-graph-grouped-bar#discussion-8" + "section": "2.2 Examining data:", + "text": "2.2 Examining data:\nWhat’s in the table? You can take a quick look at either the top of the data frame, or the bottom using one of the following commands:\n\nhead(uk_census_2021_religion)\n\n geography total no_religion christian buddhist hindu jewish\n1 North East 2647012 1058122 1343948 7026 10924 4389\n2 North West 7417397 2419624 3895779 23028 49749 33285\n3 Yorkshire and The Humber 5480774 2161185 2461519 15803 29243 9355\n4 East Midlands 4880054 1950354 2214151 14521 120345 4313\n5 West Midlands 5950756 1955003 2770559 18804 88116 4394\n6 East 6335072 2544509 2955071 26814 86631 42012\n muslim sikh other no_response\n1 72102 7206 9950 133345\n2 563105 11862 28103 392862\n3 442533 24034 23618 313484\n4 210766 53950 24813 286841\n5 569963 172398 31805 339714\n6 234744 24284 36380 384627\n\n\nThis is actually a fairly ugly table, so I’ll use an R tool called kable to give you prettier tables in the future, like this:\n\nknitr::kable(head(uk_census_2021_religion))\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\ngeography\ntotal\nno_religion\nchristian\nbuddhist\nhindu\njewish\nmuslim\nsikh\nother\nno_response\n\n\n\n\nNorth East\n2647012\n1058122\n1343948\n7026\n10924\n4389\n72102\n7206\n9950\n133345\n\n\nNorth West\n7417397\n2419624\n3895779\n23028\n49749\n33285\n563105\n11862\n28103\n392862\n\n\nYorkshire and The Humber\n5480774\n2161185\n2461519\n15803\n29243\n9355\n442533\n24034\n23618\n313484\n\n\nEast Midlands\n4880054\n1950354\n2214151\n14521\n120345\n4313\n210766\n53950\n24813\n286841\n\n\nWest Midlands\n5950756\n1955003\n2770559\n18804\n88116\n4394\n569963\n172398\n31805\n339714\n\n\nEast\n6335072\n2544509\n2955071\n26814\n86631\n42012\n234744\n24284\n36380\n384627\n\n\n\n\n\nYou can see how I’ve nested the previous command inside the kable 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. You can specify the library where the function is meant to come from by preceding it with :: as we’ve done knitr:: above. The same kind of output can be gotten using tail:\n\nknitr::kable(tail(uk_census_2021_religion))\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\ngeography\ntotal\nno_religion\nchristian\nbuddhist\nhindu\njewish\nmuslim\nsikh\nother\nno_response\n\n\n\n\n5\nWest Midlands\n5950756\n1955003\n2770559\n18804\n88116\n4394\n569963\n172398\n31805\n339714\n\n\n6\nEast\n6335072\n2544509\n2955071\n26814\n86631\n42012\n234744\n24284\n36380\n384627\n\n\n7\nLondon\n8799728\n2380404\n3577681\n77425\n453034\n145466\n1318754\n144543\n86759\n615662\n\n\n8\nSouth East\n9278068\n3733094\n4313319\n54433\n154748\n18682\n309067\n74348\n54098\n566279\n\n\n9\nSouth West\n5701186\n2513369\n2635872\n24579\n27746\n7387\n80152\n7465\n36884\n367732\n\n\n10\nWales\n3107494\n1446398\n1354773\n10075\n12242\n2044\n66947\n4048\n15926\n195041" + }, + { + "objectID": "chapter_1.html#parsing-and-exploring-your-data", + "href": "chapter_1.html#parsing-and-exploring-your-data", + "title": "2  The 2021 UK Census", + "section": "2.3 Parsing and Exploring your data", + "text": "2.3 Parsing and Exploring your data\nThe 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. Now let’s say we want to just work with the data from the West Midlands, and we’d like to omit some of the columns. We can choose a specific range of columns using select, like this:\nYou can use the filter command to do this. To give an example, filter can pick a single row in the following way:\n\nuk_census_2021_religion_wmids <- uk_census_2021_religion %>% filter(geography==\"West Midlands\") \n\nNow we’ll use select in a different way to narrow our data to specific columns that are needed (no totals!).\nSome readers will want to pause here and check out Hadley Wickham’s “R For Data Science” book, in the section, “Data visualisation” to get a fuller explanation of how to explore your data.\nIn 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." + }, + { + "objectID": "chapter_1.html#making-your-first-data-visulation-the-humble-bar-chart", + "href": "chapter_1.html#making-your-first-data-visulation-the-humble-bar-chart", + "title": "2  The 2021 UK Census", + "section": "2.4 Making your first data visulation: the humble bar chart", + "text": "2.4 Making your first data visulation: the humble bar chart\nWe’ve got a nice lean set of data, so now it’s time to visualise this. We’ll start by making a pie chart:\n\nuk_census_2021_religion_wmids <- uk_census_2021_religion_wmids %>% select(no_religion:no_response)\nuk_census_2021_religion_wmids <- gather(uk_census_2021_religion_wmids)\n\nThere 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:\n\n2.4.1 Base R\n\ndf <- uk_census_2021_religion_wmids[order(uk_census_2021_religion_wmids$value,decreasing = TRUE),]\nbarplot(height=df$value, names=df$key)\n\n\n\n\n\n\n2.4.2 GGPlot\n\nggplot(uk_census_2021_religion_wmids, aes(x = key, y = value)) +\n geom_bar(stat = \"identity\")\n\n\n2\n\nWe’ll re-order the column by size.\n\n\n\n\n\n\n2ggplot(uk_census_2021_religion_wmids, aes(x= reorder(key,-value),value)) + geom_bar(stat =\"identity\")\n\n\n\n\nLet’s assume we’re working with a data set that doesn’t include a “totals” column and that we might want to get sums for each column. This is pretty easy to do in R:\n\n1uk_census_2021_religion_totals <- uk_census_2021_religion %>% select(no_religion:no_response)\nuk_census_2021_religion_totals <- uk_census_2021_religion_totals %>%\n2 summarise(across(everything(), ~ sum(., na.rm = TRUE)))\n3uk_census_2021_religion_totals <- gather(uk_census_2021_religion_totals)\n4ggplot(uk_census_2021_religion_totals, aes(x= reorder(key,-value),value)) + geom_bar(stat =\"identity\")\n\n\n1\n\nFirst, remove the column with region names and the totals for the regions as we want just integer data.\n\n2\n\nSecond calculate the totals. In this example we use the tidyverse library dplyr(), but you can also do this using base R with colsums() like this: uk_census_2021_religion_totals <- colSums(uk_census_2021_religion_totals, na.rm = TRUE). The downside with base R is that you’ll also need to convert the result into a dataframe for ggplot like this: uk_census_2021_religion_totals <- as.data.frame(uk_census_2021_religion_totals)\n\n3\n\nIn 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()\n\n4\n\nNow plot it out and have a look!\n\n\n\n\n\n\n\nYou might have noticed 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 bind() - which can be done by columns with cbind() and rows using rbind():\n\nuk_census_2021_religion_merged <- rbind(uk_census_2021_religion_totals, uk_census_2021_religion_wmids)\n\nDo 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! This isn’t too hard to do as we can simply create a new column for each with identifiable information before we bind them:\n\nuk_census_2021_religion_totals$dataset <- c(\"totals\")\nuk_census_2021_religion_wmids$dataset <- c(\"wmids\")\nuk_census_2021_religion_merged <- rbind(uk_census_2021_religion_totals, uk_census_2021_religion_wmids)\n\nNow we’re ready to plot out our data as a grouped barplot:\n\nggplot(uk_census_2021_religion_merged, aes(fill=dataset, x= reorder(key,-value), value)) + geom_bar(position=\"dodge\", stat =\"identity\")\n\n\n\n\nIf 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 dataset column we’ve just created. Then I’ve also asked ggplot to alter the position=\"dodge\" 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.\nIf 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 dplyr feature mutate:\n\nuk_census_2021_religion_totals <- uk_census_2021_religion_totals %>% \n dplyr::mutate(perc = scales::percent(value / sum(value), accuracy = 0.1, trim = FALSE))\nuk_census_2021_religion_wmids <- uk_census_2021_religion_wmids %>% \n dplyr::mutate(perc = scales::percent(value / sum(value), accuracy = 0.1, trim = FALSE))\nuk_census_2021_religion_merged <- rbind(uk_census_2021_religion_totals, uk_census_2021_religion_wmids)\nggplot(uk_census_2021_religion_merged, aes(fill=dataset, x=key, y=perc)) + geom_bar(position=\"dodge\", stat =\"identity\")\n\n\n\n\nNow you can see a very rough comparison, which sets bars from the W Midlands data and overall 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. Our use of dplyr::mutate above can be repeated to add an infinite number of further series’ which can be plotted in bar groups.\nWe’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 ggplot really shines as a tool as you can add all sorts of things.\nThese are basically just added to our ggplot 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 scale using scale_fill_brewer. This uses a particular tool (and a personal favourite of mine) called colorbrewer. 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.\n\nggplot(uk_census_2021_religion_merged, aes(fill=dataset, x=key, y=perc)) + geom_bar(position=\"dodge\", stat =\"identity\") + scale_fill_brewer(palette = \"Set1\")\n\n\n\n\nWe might also want to add a border to our bars to make them more visually striking (notice the addition of color to the geom_bar below. I’ve also added reorder() to the x value to sort descending from the largest to smallest.\nYou can find more information about reordering ggplots on the R Graph gallery.\n\nuk_census_2021_religion_merged$dataset <- factor(uk_census_2021_religion_merged$dataset, levels = c('wmids', 'totals'))\nggplot(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\")\n\n\n\n\nWe can fine tune a few other visual features here as well, like adding a title with ggtitle and a them with some prettier fonts with theme_ipsum() (which requires the hrbrthemes() library). We can also remove the x and y axis labels (not the data labels, which are rather important).\n\nggplot(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(\"\")" + }, + { + "objectID": "chapter_1.html#is-your-chart-accurate-telling-the-truth-in-data-science", + "href": "chapter_1.html#is-your-chart-accurate-telling-the-truth-in-data-science", + "title": "2  The 2021 UK Census", + "section": "2.5 Is your chart accurate? Telling the truth in data science", + "text": "2.5 Is your chart accurate? Telling the truth in data science\nThere 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. Is the title of this chart truthful and accurate? On one hand, it is a straight-forward reference to the nature of the question asked on the 2021 census survey instrument. 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. It’s 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. But 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, but the census hasn’t capture this so we simply don’t know. If a large portion of respondents in the”Christian” category were hovering between this and another response, again, they might shift their answers when responding on a different day, perhaps having just had a conversation with a friend which shifted their thinking. 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. For this reason, 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. 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”. The 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. Finally, it is interesting to wonder exactly what it means for a person when they tick a box like this. 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.\nWhat 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, almost completely population level, sample so there is additional validity there. 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. We should also probably do something different with those non-responses:\n\nggplot(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(\"\")\n\n\n\n\nChange orientation of X axis labels + theme(axis.text.x = element_text(angle = 90, vjust = 0.5, hjust=1))\nRelabel fields Simplify y-axis labels Add percentage text to bars (or maybe save for next chapter?)" + }, + { + "objectID": "chapter_1.html#multifactor-visualisation", + "href": "chapter_1.html#multifactor-visualisation", + "title": "2  The 2021 UK Census", + "section": "2.6 Multifactor Visualisation", + "text": "2.6 Multifactor Visualisation\nOne element of R data analysis 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), 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 quantative variable (also known as bivariate data) 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.\n\nlibrary(nomisr)\n\n# Process to explore nomis() data for specific datasets\nreligion_search <- nomis_search(name = \"*Religion*\")\nreligion_measures <- nomis_get_metadata(\"NM_529_1\", \"measures\")\ntibble::glimpse(religion_measures)\n\nRows: 2\nColumns: 3\n$ id <chr> \"20100\", \"20301\"\n$ label.en <chr> \"value\", \"percent\"\n$ description.en <chr> \"value\", \"percent\"\n\nreligion_geography <- nomis_get_metadata(\"NM_529_1\", \"geography\", \"TYPE\")\n\n# Get table of Census 2011 religion data from nomis\nz <- nomis_get_data(id = \"NM_529_1\", time = \"latest\", geography = \"TYPE499\", measures=c(20301))\n# Filter down to simplified dataset with England / Wales and percentages without totals\nuk_census_2011_religion <- filter(z, GEOGRAPHY_NAME==\"England and Wales\" & RURAL_URBAN_NAME==\"Total\" & C_RELPUK11_NAME != \"All categories: Religion\")\n# Drop unnecessary columns\nuk_census_2011_religion <- select(uk_census_2011_religion, C_RELPUK11_NAME, OBS_VALUE)\n# Plot results\nplot1 <- ggplot(uk_census_2011_religion, 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))\nggsave(filename = \"plot.png\", plot = plot1)\n\nSaving 7 x 5 in image\n\n# grab data from nomis for 2011 census religion / ethnicity table\nz1 <- nomis_get_data(id = \"NM_659_1\", time = \"latest\", geography = \"TYPE499\", measures=c(20100))\n# select relevant columns\nuk_census_2011_religion_ethnicitity <- select(z1, GEOGRAPHY_NAME, C_RELPUK11_NAME, C_ETHPUK11_NAME, OBS_VALUE)\n# Filter down to simplified dataset with England / Wales and percentages without totals\nuk_census_2011_religion_ethnicitity <- filter(uk_census_2011_religion_ethnicitity, GEOGRAPHY_NAME==\"England and Wales\" & C_RELPUK11_NAME != \"All categories: Religion\" & C_ETHPUK11_NAME != \"All categories: Ethnic group\")\n# Simplify data to only include general totals and omit subcategories\nuk_census_2011_religion_ethnicitity <- uk_census_2011_religion_ethnicitity %>% filter(grepl('Total', C_ETHPUK11_NAME))" }, { "objectID": "chapter_2.html", diff --git a/hacking_religion/_book/chapter_1.html b/hacking_religion/_book/chapter_1.html index 5da2d00..edce4f2 100644 --- a/hacking_religion/_book/chapter_1.html +++ b/hacking_religion/_book/chapter_1.html @@ -210,12 +210,16 @@ div.csl-indent {

Table of contents

@@ -240,8 +244,8 @@ div.csl-indent { -
-

2.1 Your first project: building a pie chart

+
+

2.1 Your first project: the UK Census

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.

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, “data import”.

In the example below, we’re going to read 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 “read.csv”. 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:

@@ -272,8 +276,9 @@ i Use the conflicted package (<http://conflicted.r-lib.org/>) to force all
uk_census_2021_religion <- read.csv(here("example_data", "census2021-ts030-rgn.csv")) 
-
-

2.1.1 Examining data:

+
+
+

2.2 Examining data:

What’s in the table? You can take a quick look at either the top of the data frame, or the bottom using one of the following commands:

head(uk_census_2021_religion)
@@ -535,29 +540,27 @@ i Use the conflicted package (<http://conflicted.r-lib.org/>) to force all
-
-

2.1.2 Parsing and Exploring your data

+
+

2.3 Parsing and Exploring your data

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. Now let’s say we want to just work with the data from the West Midlands, and we’d like to omit some of the columns. We can choose a specific range of columns using select, like this:

You can use the filter command to do this. To give an example, filter can pick a single row in the following way:

-
uk_census_2021_religion_wmids <- uk_census_2021_religion %>% 
-  filter(geography=="West Midlands")  
+
uk_census_2021_religion_wmids <- uk_census_2021_religion %>% filter(geography=="West Midlands")  

Now we’ll use select in a different way to narrow our data to specific columns that are needed (no totals!).

Some readers will want to pause here and check out Hadley Wickham’s “R For Data Science” book, in the section, “Data visualisation” to get a fuller explanation of how to explore your data.

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.

-
-
-

2.2 Making your first chart

+
+

2.4 Making your first data visulation: the humble bar chart

We’ve got a nice lean set of data, so now it’s time to visualise this. We’ll start by making a pie chart:

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)

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:

-
-

2.2.0.1 Base R

+
+

2.4.1 Base R

df <- uk_census_2021_religion_wmids[order(uk_census_2021_religion_wmids$value,decreasing = TRUE),]
 barplot(height=df$value, names=df$key)
@@ -566,8 +569,8 @@ i Use the conflicted package (<http://conflicted.r-lib.org/>) to force all
-
-

2.2.0.2 GGPlot

+
+

2.4.2 GGPlot

ggplot(uk_census_2021_religion_wmids, aes(x = key, y = value)) +
   geom_bar(stat = "identity")
@@ -575,7 +578,7 @@ i Use the conflicted package (<http://conflicted.r-lib.org/>) to force all
2
-We’ll re-order the column by size. +We’ll re-order the column by size.
@@ -598,19 +601,19 @@ i Use the conflicted package (<http://conflicted.r-lib.org/>) to force all
1
-First, remove the column with region names and the totals for the regions as we want just integer data. +First, remove the column with region names and the totals for the regions as we want just integer data.
2
-Second calculate the totals. In this example we use the tidyverse library dplyr(), but you can also do this using base R with colsums() like this: uk_census_2021_religion_totals <- colSums(uk_census_2021_religion_totals, na.rm = TRUE). The downside with base R is that you’ll also need to convert the result into a dataframe for ggplot like this: uk_census_2021_religion_totals <- as.data.frame(uk_census_2021_religion_totals) +Second calculate the totals. In this example we use the tidyverse library dplyr(), but you can also do this using base R with colsums() like this: uk_census_2021_religion_totals <- colSums(uk_census_2021_religion_totals, na.rm = TRUE). The downside with base R is that you’ll also need to convert the result into a dataframe for ggplot like this: uk_census_2021_religion_totals <- as.data.frame(uk_census_2021_religion_totals)
3
-In order to visualise this data using ggplot, we need to shift this data from wide to long format. This is a quick job using gather() +In order to visualise this data using ggplot, we need to shift this data from wide to long format. This is a quick job using gather()
4
-Now plot it out and have a look! +Now plot it out and have a look!
@@ -648,14 +651,90 @@ i Use the conflicted package (<http://conflicted.r-lib.org/>) to force all

-

Now you can see a very rough comparison

-

Add time series data for 2001 and 2011 census, change to grouped bar plot:

-

https://r-graphics.org/recipe-bar-graph-grouped-bar#discussion-8

+

Now you can see a very rough comparison, which sets bars from the W Midlands data and overall 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. Our use of dplyr::mutate above can be repeated to add an infinite number of further series’ which can be plotted in bar groups.

+

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 ggplot really shines as a tool as you can add all sorts of things.

+

These are basically just added to our ggplot 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 scale using scale_fill_brewer. This uses a particular tool (and a personal favourite of mine) called colorbrewer. 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.

+
+
ggplot(uk_census_2021_religion_merged, aes(fill=dataset, x=key, y=perc)) + geom_bar(position="dodge", stat ="identity") + scale_fill_brewer(palette = "Set1")
+
+

+
+
+

We might also want to add a border to our bars to make them more visually striking (notice the addition of color to the geom_bar below. I’ve also added reorder() to the x value to sort descending from the largest to smallest.

+

You can find more information about reordering ggplots on the R Graph gallery.
+
+
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")
+
+

+
+
+

We can fine tune a few other visual features here as well, like adding a title with ggtitle and a them with some prettier fonts with theme_ipsum() (which requires the hrbrthemes() library). We can also remove the x and y axis labels (not the data labels, which are rather important).

+
+
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("")
+
+

+
+
+
+
+
+

2.5 Is your chart accurate? Telling the truth in data science

+

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. Is the title of this chart truthful and accurate? On one hand, it is a straight-forward reference to the nature of the question asked on the 2021 census survey instrument. 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. It’s 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. But 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, but the census hasn’t capture this so we simply don’t know. If a large portion of respondents in the”Christian” category were hovering between this and another response, again, they might shift their answers when responding on a different day, perhaps having just had a conversation with a friend which shifted their thinking. 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. For this reason, 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. 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”. The 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. Finally, it is interesting to wonder exactly what it means for a person when they tick a box like this. 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.

+

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, almost completely population level, sample so there is additional validity there. 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. We should also probably do something different with those non-responses:

+
+
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("")
+
+

+
+
+

Change orientation of X axis labels + theme(axis.text.x = element_text(angle = 90, vjust = 0.5, hjust=1))

+

Relabel fields Simplify y-axis labels Add percentage text to bars (or maybe save for next chapter?)

+
+
+

2.6 Multifactor Visualisation

+

One element of R data analysis 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), 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 quantative variable (also known as bivariate data) 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.

+
+
library(nomisr)
+
+# Process to explore nomis() data for specific datasets
+religion_search <- nomis_search(name = "*Religion*")
+religion_measures <- nomis_get_metadata("NM_529_1", "measures")
+tibble::glimpse(religion_measures)
+
+
Rows: 2
+Columns: 3
+$ id             <chr> "20100", "20301"
+$ label.en       <chr> "value", "percent"
+$ description.en <chr> "value", "percent"
+
+
religion_geography <- nomis_get_metadata("NM_529_1", "geography", "TYPE")
+
+# Get table of Census 2011 religion data from nomis
+z <- nomis_get_data(id = "NM_529_1", time = "latest", geography = "TYPE499", measures=c(20301))
+# Filter down to simplified dataset with England / Wales and percentages without totals
+uk_census_2011_religion <- filter(z, GEOGRAPHY_NAME=="England and Wales" & RURAL_URBAN_NAME=="Total" & C_RELPUK11_NAME != "All categories: Religion")
+# Drop unnecessary columns
+uk_census_2011_religion <- select(uk_census_2011_religion, C_RELPUK11_NAME, OBS_VALUE)
+# Plot results
+plot1 <- ggplot(uk_census_2011_religion, 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))
+ggsave(filename = "plot.png", plot = plot1)
+
+
Saving 7 x 5 in image
+
+
# grab data from nomis for 2011 census religion / ethnicity table
+z1 <- nomis_get_data(id = "NM_659_1", time = "latest", geography = "TYPE499", measures=c(20100))
+# select relevant columns
+uk_census_2011_religion_ethnicitity <- select(z1, GEOGRAPHY_NAME, C_RELPUK11_NAME, C_ETHPUK11_NAME, OBS_VALUE)
+# Filter down to simplified dataset with England / Wales and percentages without totals
+uk_census_2011_religion_ethnicitity <- filter(uk_census_2011_religion_ethnicitity, GEOGRAPHY_NAME=="England and Wales" & C_RELPUK11_NAME != "All categories: Religion" & C_ETHPUK11_NAME != "All categories: Ethnic group")
+# Simplify data to only include general totals and omit subcategories
+uk_census_2011_religion_ethnicitity <- uk_census_2011_religion_ethnicitity %>% filter(grepl('Total', C_ETHPUK11_NAME))
+
-

References