Posted on

moRe aRchaeology

Using R to visualise Archaeological data.

I like R, the computer language focussed on data analysis, and I like Archaeology (which may come as a surprise to all the people who have heard me complain about my job, but that’s another matter entirely). So, in my ongoing mission to learn how to use R properly it makes sense that I would be trying to use it for archaeological ends. You can’t beat a nice visualisation of a massive and borderline unreadable spreadsheet that makes it so much easier to pull out patterns and correlations from the data.

One of the problems that I have come across with learning R is finding suitable data-sets for me to work from. Archaeologists are very very very bad at publishing their raw data so that others can carry out analysis in order to see if their results can be replicated. Archaeology, by dint of how we recover data in the form of excavation, is an inherently destructive process. A site cannot be excavated twice. Especially not if, after the first time it was excavated, it was then buried underneath a new road or housing development. Which is exactly what happens to the vast majority of archaeological sites which are excavated being as most archaeological excavation is carried out prior to a new building project of on kind or another.

Which is why it is extremely important that archaeological data is shared so that other archaeologists can use the data recovered and thus drive the discipline forward. Unfortunately this is not always the case and the raw data from an excavation can sit indefinitely in the archives of the local heritage authority or on the hard-drives of the excavation firm who carried out the work. This is especially the case in the region where I work, Niedersachsen/Bremen, where almost no archaeological data is publicly available (outside of the god-awful ‘Denkmal-Atlas’ which may be nice for lay people, not so great for carrying out scientific work) and one must request any data from the authorities.

I am loath to go through the process of asking the local authorities for data when it is, mostly, just for me to faff around with whilst I learn a new programming language. When I have a decent research proposal then maybe. But, for now, I am having to try and find open data sources online.

There are some places where data can be found such as the Journal of Open Archaeology Data or the Archaeological Data Service but they rarely, if ever, contain data from Germany. Germany is something of a black hole when it comes to archaeological data. So I was rather happy when I found out that Kiel University has an online space for post-graduate students to deposit their data.

Naturally I downloaded everything I could get my grubby little hands on. Which then led me on to a revelation, something that I suppose I have down for a long time, that we archaeologists really really bloody suck at organising data…

We can’t really be blamed for that I suppose. After all, we were never taught data management in university! And if we were, it was probably by someone who was an archaeologist who self learned a bit of data management on the side. (A bit like I am doing with R) Rather than being taught by an actual data scientist.

(I know that some archaeologists will have learned properly, I am just going of my own experience at university. Oh, and through knowing a lot of archaeologists who also suck at this stuff.)

Rant over and on to the really nerdy stuff.

As part of learning R I am wanting to learn how to process data into a way that I can use for visualisation. Part of this will involve cleaning the data (just as well that archaeologists are messy so-and-sos) and then using R to generate a variety of visualisation which can then be used to analyse the data.

The data set that I chose to play with today comes from the paper Loom Weights in Bronze Age Central Europe by Jutta Kneisel and Stefanie Schaefer-Di Maida from in the book The Textile Revolution in Bronze Age Europe. Production, Specialisation, Consumption by Serena Sabatini and Sophie Bergerbrant(Eds.)

The data was issued under a Creative Commons CC BY-NC-SA license, and therefore so is this wee blog post.

Before I start, I want to make clear that I may well cuss and moan about the data that I downloaded, but that is in no way a comment on the work of the authors. Merely on the way that they have arranged their data. Which, as I just said, isn’t the sort of thing that most archaeologists are trained in and I deeply appreciate that they made their data available for all.

The below is 99% just so that I can remember the process at a later date or have something to refer back to.

Method

Step 1 – Get the data and import it into RStudio

First off, download the data from here and extract it into your project folder. Within the .zip file is an Excel workbook (first complaint, please don’t use Excel it has a really bad habit of thinking that it is cleverer than you and so adjusts the format of the cells, as we shall come back to.) The .zip also contains the really nice visualisations which Kneisel and Schaefer-Di Maida created for their chapter.

An Excel workbook may seem like a sensible option for storing your data, after all – one file can contain several spreadsheets meaning that you don’t have to have multiple things open on your computer at a time. It isn’t however a future proof way to archive data, try opening a Word doc from 1995 and see what I mean, and there is also the above mentioned problem.

So, the first thing I need to do is export each sheet as a .csv. A .csv is an extremely basic way of storing data. It is columns and rows like a spreadsheet but with the ‘columns’ being divided by a comma. (Comma Separated Values, csv) It is also simply a text file, meaning that any text editing program can open it, on any platform, and it doesn’t matter if the file was created in 1995 or 2095.

So, with each sheet as an individual .csv into my project folder, I can begin getting the data into Rstudio.

To do this I use the read.csv function of R. The format of the command is as follows.

cyl <- read.csv(“Loomweights_cylindrical.csv”)
disc <- read.csv(“Loomweights_disc-shaped.csv”)
others <- read.csv(“Loomweights_others.csv”)
pyra <- read.csv(“Loomweights_pyramidal.csv”)
ring <- read.csv(“Loomweights_ring-shaped.csv”)
sph <- read.csv(“Loomweights_spherical.csv”)
tri <- read.csv(“Loomweights_triangle.csv”)

What this does is tell R to read the .csv files and store them as dataframes with the first word in each command being the name of the dataframe. <- being something like ‘=’ but if R saw ‘=’ it would look for ‘cyl’ and, not finding it because it hasn’t been created yet, throw an error.

To check that the dataframes have been created correctly we can use the ‘head’ command to print the first few lines from the data table. Here are the results of > head(cyl)

  id                    site  site.Nr.         x        y number.of.weights minimum.number.of.weights Gewicht Gewicht_N
1  1                Allstedt       E10 11.392681 51.43134                 1                         1                NA
2  2 Alt Gaul OT von Wriezen           14.097146 52.73958                 1                         1                NA
3  3           Arbon Bleiche 7, Fpl. 2  9.431606 47.51672                23                        23    1800      1800
4  4               Archlebov           17.003932 49.04341                 1                         1                NA
5  5          Aub-Burgerroth           10.031506 49.53399                 1                         1                NA
6  6             B6N_Fundst.     VII 2 11.118200 51.81700                 1                         1                NA
  district.parish        country        type ornamented puncture.outside finger.dents Cross lines.outside
1    Sangerhausen Sachsen-Anhalt zylindrisch   verziert                                                  
2                    Brandenburg                                                                         
3     Kt. Thurgau        Schweiz zylindrisch   verziert                             x                    
4    okr. Hodonín     Tschechien  o. Angaben                                                             
5        Würzburg         Bayern zylindrisch   verziert                                                 x
6                 Sachsen-Anhalt zylindrisch                                                             
  ornamentation.remarks find.context remarks          period
1                         Einzelfund                        
2                           Siedlung                        
3                           Siedlung                        
4                           Siedlung          Verterov Grppe
5     zwei Linien außen     Siedlung         Kupferzeitlich?
6                                     Walze?                
                                                                      literature Chronology length width.cross.section
1                                                                      Zich 1996        FBZ                           
2                                                               Fundortdatenbank                                      
3 Gleser 2007, Hochuli 1994, Taf. 80, 734-36; Taf. 81, 744-745; Taf. 82, 750-751        FBZ                           
4                                                                    Gleser 2007        FBZ                           
5                                                                    Gleser 2007 Kupferzeit                           
6                                                          mündl. Mitt. C. Rinne         BZ                           
   X  X.1        X.2 X.3 X.4 X.5         X.6 X.7
1 NA                  NA  NA  NA                
2 NA                  NA  NA  NA                
3 NA                  NA  NA  NA                
4 NA                  NA  NA  NA                
5 NA                  NA  NA  NA                
6 NA nein Webgewicht  NA   4  36 0,02- Sohle  

The data is all there, but it is still pretty messy.

What I would like to do with R is create some visualisations to see if there is any correlation between the shape of the Loom Weights and the region in which they are found. Are styles of loom weight a local thing (for local people!). To this end, I would like to combine all of the data-frames into a single data-frame so that I am only having to refer to a single data-frame in my code, making it a lot easier to read and understand. To do this I will need to use ‘dplyr’ which is a powerful tool for data manipulation in R.

What I want to do is create a new data-frame, let’s call it ‘loom_weights’, but I only want the data from a handful of the columns in the .csv files. I don’t need, for example, the literature relating to the site or the dimensions of the weights themselves. So I need to tell dplyr what data to take and from which dataframes.

First I will make a list of the data-frames that I would like to extract data from.

And this, I do thus:

dfs <- list(cyl, disc, others, pyra, ring, sph, tri)

This creates a list of all the data-frames. Next I need to tell R what I want the new data-frame to be called and which frames, from the list, to work on.

And this, I do thus:

loom_weights <- bind_rows(lapply(dfs, function(df) {
df %>% select(site, site.Nr., x, y, number.of.weights, type, ornamented, find.context, period, remarks, Chronology)
}))

Except that I don’t as R immediately throws errors due to the formatting of the data. You see, computer languages (well, the two with which I am familiar, R and Python) like data in columns to all be of the same sort. So, all strings (strings of characters), integers (whole numbers), real (decimal numbers), dates, and so on. The problem that we have here is threefold. First, there are some entries in the columns that contain no data and so have the value ‘NA’ which is a pain if R expects that to be a column of numbers. So we need to replace those ‘NA’ with ‘0’.

Then there are the Site Numbers. Some of these are numeric, some are just letters, and others are a mix. Therefore I have to tell R to treat the Site.Nr column as a string. Luckily we don’t have to do any calculations with the values in the Site.Nr column, so it is ok to treat them as strings. (You can’t do mathematical calculations with strings, only with real numbers or integers).

site.Nr. = as.character(site.Nr.)

We also have the problem that I mentioned earlier, where Excel thinks that it is clever. Some of the values in the ‘x’ column have been converted to a date format…

Replacing NA with 0 is pretty easy, we just adjust our code like so:

loom_weights <- bind_rows(lapply(dfs, function(df) {
df %>%
select(site, site.Nr., x, y, number.of.weights, type, ornamented, find.context, period, remarks, Chronology) %>%
mutate(across(everything(), ~ ifelse(is.na(.), 0, .))) # Replace NA with 0
}))

Here we use %>% to pipe the selected data through the mutate function which seeks out all instances of NA and replaces them with 0.

Sorting out the date issue is a bit more tricky.

I could, and probably should, go through the spreadsheet in Excel and ensure that all cells containing coordinates are set to display the numbers as they were entered, not as Excel thinks that they should be. But, this is about R and learning so let’s try and do it another way.

First I create a function to clean up the entries that are formatted as dates back to real numbers. I am going to be making a huge assumption here in that the first two digits of the value should be followed by a dot rather than a slash and that the second slash should simply be discarded. What could go wrong eh?

clean_date_format <- function(column) {
column <- as.character(column) # Ensure it’s a character type
column <- gsub(“^([0-9]{2})/([0-9]{2})/[0-9]{4}$”, “\\1.\\2”, column) # Replace format
return(column)
}

This function can then be called upon later in the code when the data is being processed.

So, here is the final code for tidying up the dataframes into a single dataframe and dealing with NA values, strings where there should be integers, and getting rid of those pesky dates.

loom_weights <- bind_rows(lapply(dfs, function(df) {
df %>%
select(site, site.Nr., x, y, number.of.weights, type, ornamented, find.context, period, remarks, Chronology) %>%
mutate(
# Convert ‘site.Nr.’ to character (string) type
site.Nr. = as.character(site.Nr.),
# Clean the ‘x’ and ‘y’ columns for date-like entries
x = clean_date_format(x),
y = clean_date_format(y),
# Convert ‘x’ and ‘y’ back to numeric (after cleaning), replacing non-numeric with NA
x = as.numeric(x),
y = as.numeric(y),
# Convert ‘number.of.weights’ to numeric, replacing non-numeric entries with NA
number.of.weights = as.numeric(number.of.weights),
# Replace NA with 0 in numeric columns
across(where(is.numeric), ~ ifelse(is.na(.), 0, .)),
# Replace NA with an empty string in character columns
across(where(is.character), ~ ifelse(is.na(.), “”, .))
)
}))

There, that should work. And it does!

I have a data-frame called ‘loom_weights’ and head(loom_weights) gives me the following.

   site  site.Nr.         x        y number.of.weights        type ornamented find.context
1                Allstedt       E10 11.392681 51.43134                 1 zylindrisch   verziert   Einzelfund
2 Alt Gaul OT von Wriezen           14.097146 52.73958                 1                            Siedlung
3           Arbon Bleiche 7, Fpl. 2  9.431606 47.51672                23 zylindrisch   verziert     Siedlung
4               Archlebov           17.003932 49.04341                 1  o. Angaben                Siedlung
5          Aub-Burgerroth           10.031506 49.53399                 1 zylindrisch   verziert     Siedlung
6             B6N_Fundst.     VII 2 11.118200 51.81700                 1 zylindrisch                        
           period remarks Chronology         z_x         z_y
1                                FBZ -0.08057198  0.30016554
2                                     0.44291980  0.42501876
3                                FBZ -0.46016892 -0.07343182
4  Verterov Grppe                FBZ  1.00557400  0.07227032
5 Kupferzeitlich?         Kupferzeit -0.34404883  0.11908927
6                  Walze?         BZ -0.13370210  0.33697113

Step 2 – Visualisation

OK, let’s start making pretty visualisations of the data.

First we need to install the necessary packages into R, in this case we will be using ggplotly for data visualisation.

install.packages(“ggplot2”)
library(ggplot2)

will install and load the packages.

To make a simple scatterplot we use the following:

ggplot(loom_weights, aes(x = x, y = y, color = type)) +
geom_point(size = 3, alpha = 0.7) +
theme_minimal() +
labs(title = “Geographic Location of Loom Weights by Type”,
x = “X Coordinate”,
y = “Y Coordinate”,
color = “Type”)

This will use ggplotly to read loom_weights and use the x and y values from those columns to plot each point on a Cartesian grid. ‘color = type’ says that each point is to have its colour defined by the value in the ‘type’ column. ‘geom_point’ defines how the points themselves will look and ‘labs’ refers to the labels of the plot.

And this is what we get.

 

Hmmmm, that I doesn’t look too great. Not too shabby, but not too great. But we also have those strange outliers that look to be very far away from the study area. I get the strange feeling that these are the sites where the coordinates were in date format. What can go wrong eh?

Well, I’m not going to go back through and try to fix them at the moment. So I need to figure out which of the rows are so far away from the study area and I shall do this using the standard deviation of all points and exclude any that are too far outside of the SD.

We do this by calculating the Z value for each point and filtering out any rows where the Z score is way outside the SD for the plot.

loom_weights <- loom_weights %>%
mutate(z_x = (x – mean(x, na.rm = TRUE)) / sd(x, na.rm = TRUE),
z_y = (y – mean(y, na.rm = TRUE)) / sd(y, na.rm = TRUE))
# Filter out rows where the z-score is outside the range of [-3, 3] for either x or y
loom_weights_filtered <- loom_weights %>%
filter(abs(z_x) <= 3 & abs(z_y) <= 3)
# Remove the z_x and z_y columns after filtering
loom_weights_filtered <- loom_weights_filtered %>%
select(-z_x, -z_y)

That looks much better! There are however a bunch of ‘type’ values there that we don’t really need. If I am wanting to see whether there is a geographic correlation between the forms of loom weight I don’t need ones where there is no description of the form (ohne Angabe/n in this case) or where it is a sherd that has a hole drilled through it (durchbohrte Bodenscherbe) or if it is just a fragment of a loom weight.

So, let’s filter these rows out and see what we get.

#using ‘c’ to create a vector containing the rows to be filtered out
excluded_types <- c(‘Fragment’, ‘durchbohrte Bodenscherbe’, ‘o, Angaben’, ‘o. Angabe’, ‘o. Angaben’, ‘o. Angaben, verziert’)
# Filter out rows where ‘type’ is one of the excluded values
loom_weights_type_filtered <- loom_weights_filtered %>%
filter(!(type %in% excluded_types))
# Display the filtered dataframe
head(loom_weights_type_filtered)
#Same code as previously but for the new dataframe
ggplot(loom_weights_type_filtered, aes(x = x, y = y, color = type)) +
geom_point(size = 3, alpha = 0.7) +
theme_minimal() +
labs(title = “Geographic Location of Loom Weights by Type”,
x = “X Coordinate”,
y = “Y Coordinate”,
color = “Type”)

You will see from the previous snippets of code that we are creating more and more data-frames as we go on. This means that if… lol, when I mess something up I can always roll back and work on a previous data-frame.

Let’s see how it looks.

Super! That is much better and less cluttered by data points which aren’t going to help us see what we want to see.

We can defiitely see something of a pattern here, but the colours of the points are all so similar that it is difficult to tell whether a point is pyramidal or oval.

There is a package for R called viridis which may give us a colour palette with more contrast.

install.packages(“viridis”)
library(viridis)
ggplot(loom_weights_type_filtered, aes(x = x, y = y, color = type)) +
geom_point(size = 3, alpha = 0.7) +
scale_color_viridis(discrete = TRUE) + # Use the viridis palette
theme_minimal() +
labs(title = “Geographic Location of Loom Weights by Type”,
x = “X Coordinate”,
y = “Y Coordinate”,
color = “Type”)

Hmmm, better, but not quite there yet.

Let’s try a way to define the boundaries of the various types by drawing ovals around them.

library(ggplot2)
library(viridis)

# Plot with ellipses and a single legend
ggplot(loom_weights_type_filtered, aes(x = x, y = y, color = type)) +
geom_point(size = 3, alpha = 0.7) +
stat_ellipse(aes(fill = type), geom = “polygon”, alpha = 0.2, color = NA, show.legend = FALSE) + # Add ellipses without separate legend
scale_color_viridis(discrete = TRUE) + # Use distinct color palette for both
scale_fill_viridis(discrete = TRUE, guide = “none”) + # Ensure fill uses same color and hide the fill legend
theme_minimal() +
labs(title = “Geographic Location of Loom Weights by Type”,
x = “X Coordinate”,
y = “Y Coordinate”,
color = “Type”)

Hmmm, better but also not great. But I think that will do for now. Next time I may try making something a bit more interactive and see if that helps. Or perhaps laying the points across a map….

 

Posted on

WheRe’s my Cow?*

I am rather fond of a good map, and especially a good map that has some kind of archaeological content. Due to this I tend to spend an inordinate amount of time both making maps and learning new and interesting ways to make them. This has led to me now being something of the “GIS-guy” at my new workplace. Well, the “QGIS guy” as I spent around 5 minutes working with ArcGIS in about 2012 before realising that it would be better for my wallet to focus on the open source side of things. Not that I mind being the QGIS-guy, I am much happier working at a computer than freezing half to death somewhere in the north of Germany in the middle of winter. FAR happier! XD

We recently finished an excavation at the beginning of December last year. Gott sei dank, it is bloody nippy out at the moment! Quite where it was I am not allowed to say because the German authorities are extremely sensitive about that sort of thing. I can however talk about it in more general terms. Which I am going to do as it was quite different to everywhere else that I have dug in my career so far. Almost every dig that I have worked on has been in something of a rural setting. This has meant that there has, in general, been no really complicated stratigraphy.

Stratigraphy gets complicated when there has been a large amount of activity in a place and later activities have disturbed or cut through earlier activities. So in a city or town that has been continuously occupied for the last 2,000 years there could be a house from the 1920s whose foundations cut through the remains of a medieval building that stood on the same spot which itself was cut into a Roman structure. It can be a real puzzle to figure out.

example of archaeological stratigraphy
© Canterbury Archaeological Trust

This isn’t often the case in a rural context where perhaps houses and barns may have been built one atop another but not usually repeatedly over thousands of years. I’m writing in a northern European context here, it is quite possibly very different elsewhere.

The techniques for excavating in a rural setting are also quite different to an urban one. A rural setting will often, in my experience, be a lot simpler to excavate and document. In the areas I have worked we will use an excavator, a “Bagger” in the local parlance, to strip away the upper soil until we reach the soil set down in the last glacial maximum. We will then record what we see in a flat plane before excavating features individually. This initial recording will give us a plan drawing looking something like this.

We can see from this that we have some sort of structure, possibly a small house or barn. Lovely isn’t it?

It’s also pretty straight forward to interpret compared to urban excavations which can, as  seen above, have extremely complicated stratigraphy. I haven’t done much in the way of urban excavation and haven’t done any analysis or GIS work with those projects that I have worked on.

I started work with a new firm this last summer and my first dig with them was in an urban setting but was quite unlike anything I have worked on before, rural or urban. There was little in the way of structures aside from a smattering of posts, possibly animal enclosures, and a couple of large trenches criss-crossing the excavated area. What there was however was a metric f*ck-ton of animal skeletons. Some appearing to have been intentionally buried, others less so.

In order to try and figure out what was going on there the local heritage body asked for a document with information on each of the skeletons with their locations, photographs, and so on. Seeing as I’m the GIS/map nerd in the office that task was given to me. Putting together a map that just shows the locations of each of the skeletons without the other documented features is a simple enough job using QGIS. The only problem here is that a map is, by its nature, two dimensional and it is important to be able to show the depth at which the skeletons were found in relation to one another.

humorous image of an excavation plan
(and now we understand the title of this post)

In order to do this I decided to use a scatterplot diagram using the height above sea-level as the ‘Y’ axis and the point name/number as the ‘X’ axis. This would allow me to clearly show the difference in depth between the various skeletons. I am going to describe my method here so that, hopefully, others may find it useful and because my memory is absolutely awful and I would like to be able to refer back to something next time I have to do this.

My process can be broken down into 5 steps. Even if step one does have 8 ‘sub-steps’.

Steps

  1. Export data from QGIS as .csv
    1. Filter for useful points
    2. Select points relating to areas with skeletons
    3. Make a new layer
    4. Use Field Calculator to calculate mean coordinates
    5. Clean up ‘bemerkung’ fields with REGEX
    6. Create points layer from table
    7. Delete duplicates by attribute
    8. Export as .csv
  2. Read .csv into a dataframe in Rstudio
  3. Generate Scatterplot
  4. Tweak Scatterplot until it is ‘just so’
  5. Automate making a Scatterplot highlighting each point in turn.

Before starting I should talk briefly about how we excavated this particular site. Because of the particular issues with this particular site, rather than recording the entire area we broke it down into smaller areas, Flächezeichnung, focused on where we had seen archaeological features. We would then document and excavate these ‘Flz’ fully before moving onto the next one. This resulted in a plan drawing looking something like this below. More of a patchwork than a normal excavation with each outline being an excavated area.

It’s almost like abstract art

To document each area we measure the outlines of the features in with a Total Station. Each point is recorded with a series of letters and numbers that denote things like what is being measured, its feature number, and so on. This data is then exported and imported into QGIS in order to draw the plan and begin analysis.

QGIS + Steps 1.1-1.8

My initial thought when approaching this problem was to use the DataPlotly plugin for QGIS. DataPlotly allows one to make number of attractive charts to help illustrate geospatial data. It’s a really useful plugin but, unfortunately, it isn’t very easily tweakable. I was able to generate a basic scatterplot but unable to highlight specific data points to show which skeleton was being discussed in the document.

Doesn’t really *pop*, does it?

To do this I needed first to generate a single coordinate that would represent the skeleton and the feature in which it was found. Within each ‘Flz’ we measured many, many, many points for the outlines of features, archaeological and geological, and anything found within such as pottery, glass, metal, and (of course) skeletons. This means that a single ‘Flz’ can have upwards of 500 individual measured points. I needed to reduce these down to a single point.

One of the sets of measurements we take are for something called “structure from motion”. SfM is a way of creating a three dimensional image from a set of two dimensional photographs. Each set of SfM photographs uses control points which are measured with the Total Station and then used to place the generated 3D model into the correct place in a map. These control points are evenly spaced around the Flz and so will be perfect for finding the mean average coordinates of the Flz as a whole.

Step 1.1: Filter the points layer for the value ‘SFM’ meaning that from this point on, when working with this points layer, QGIS will only work with those points.

Step 1.2: Open the Attribute Table of the points layer in QGIS. Then manually select each of the Flz containing skeletons.

Step 1.3: Export each of the selected points to a new temporary layer.

Step 1.4:  Use the Graphical Modeler to run three regular expressions over the new points layer. The Graphical Modeller allows one to run a series of algorithms in a chain when you’re too lazy to do it multiple times. I made a model, see below, that ran the following expressions over the new layer.

mean("x", group_by:="bemerkung")

mean("y", group_by:="bemerkung")

mean("z", group_by:="bemerkung")

(‘bemerkung’ being the column containing the data referring to which Flz is being recorded)

A simple model for the terminally lazy

This added three new columns to the Attribute Table of the new layer, mean_x, mean_y, and mean_z with each point containing the mean average coordinates for the group.

Step 1.5: This left me with a new layer made up only the SFM points. However, due to the way that we used to record SFM points in the field the ‘bemerkung’ column which I am using to group points together doesn’t simply read ‘FLZxxx’. Rather it reads SFM_FLZxxx_x’. So I needed to again use the Field Calculator to update the ‘bemerkung’ field and remove the extraneous characters.

regexp_replace("bemerkung", '^SFM_FZ|_\\d+$', '')

This expression essentially says: replace ‘SFM_FZ’ at the beginning (^SFM_FZ) and any trailing underscore and number at the end (_\\d+$) with an empty string. Cool.

Step 1.6: However this still leaves me with four points for each FLZ and I need a single point with the x, y, and z values from the ‘mean_x, y, and z’ values of my new ‘mean_values’ layer. The “easiest” way to do this is to use the ‘Create points layer from table’ tool which will create a nice central point for each FLZ. Well, it will create four central points which is no good.

Step 1.7: So, I then use the ‘Delete duplicates by attribute’ tool and, at last, I have a layer that I can feed into DataPlotly. However, as shown above, DataPlotly doesn’t really do what I need. So now I’m going to have to make it complicated.

Well, more complicated. :/

Step 1.8: Export the layer as a .csv, in this case it is called ‘tierskelett_flz_centroid.csv’. (Tier=animal, Skelett=skeleton)

R + RStudio

This is where it gets super nerdy.

Now we are going to start using ‘R’. R is a programming language that is especially good at data visualisation. We will be using this with a program called Rstudio which is a development environment that makes things a little bit easier to handle than just writing line after line of code.

Step 2:

In Rstudio I create a new RProject and a  folder, in this case both called ‘tierskelett_plots’, into which I copy the .csv file exported from QGIS.

First up I want to read the .csv file into R so that R can treat it as a dataframe. I do this with the command:

readfile <- read.csv("tierskelett_flz_centroid.csv")

To ensure that it has been read correctly I can check the first few lines of the table with the following command:

head(readfile)

This will give a readout like something like this

  bemerkung        x       y        z
1       239 227539.0 6677714 1.757525
2       259 227545.5 6677727 2.509575
3       312 227549.1 6677731 2.230800
4       234 227539.0 6677714 2.027550
5       311 227557.3 6677734 2.491500
6       292 227550.8 6677726 2.272125

(the x and y coordinates above are nonsense as I wouldn’t want to be sharing actual location data with you animals.)

Step 3: Make a simple scatterplot to see that it works. To do this I use the following code:

> plot(readfile$bemerkung, readfile$z,
+      pch = 16, col = "blue",
+      xlab = "bemerkung", ylab = "z",
+      main = "Streudiagramm, das die Tiefenbeziehung von Tier-Skeletten darstellt.")

In the above code ‘pch’ refers to the form that the points will take in the scatterplot, the ‘plotting character’, which in this case, ’16’, is a circle. See the bottom of this article for a full list of all 24 possible plotting characters. ‘col’ refers to the colour of the points, ‘xlab’ and ‘ylab’ refer to the labels of the x and y axes, whilst ‘main’ refers to the title of the diagram. Which gives us the following plot. Not so different to the DataPlotly one generated in QGIS.

That’s nice, but I want a couple of extra things of my scatterplot. Firstly I want labels, and secondly I want a way to highlight a single point so that I can include the plot on each page of my document showing the skeleton in relation to others on the site.

Step 4: 

First off to add the label I need to change my code like so:

> plot(readfile$bemerkung, readfile$z, 
+      pch = 16, col = "blue", 
+      xlab = "bemerkung", ylab = "z", 
+      main = "Streudiagramm, das die Tiefenbeziehung von Tier-Skeletten darstellt.")
> text(readfile$bemerkung, readfile$z, 
+      labels = readfile$bemerkung, 
+      pos = 1, offset = 0.5, col = "black")

Here we tell R to add labels to the points by referencing the .csv column ‘bemerkung’ with the line “labels = readfile$bemerkung,”, with ‘pos’ being the position, ‘offset’ the (you guessed it) offset, and again ‘col’ being the colour. Unfortunately many of our points are quite close together and so the labels look really messy.

So, that’s not great and certainly not something that I would be wanting to send to the local heritage authority. Instead of the base R plotting functions we shall install a couple of other R packages which give extra functionalities. We will install ggplot2 which expands the possibilities with drawing plots and ggrepel which does really clever geometry stuff in order to prevent ggplot2 overlapping the  labels. We install these with the following commands:

install.packages("ggplot2")

install.packages("ggrepel")

We then need to make sure that R will use these packages by adding them as libraries:

library(ggplot2)

library(ggrepel)

Now we can generate the scatterplot with ggplot and ggrepel.

 ggplot(data = readfile, aes(x = bemerkung, y = z, label = bemerkung)) +
     geom_point(shape = 16, color = "blue") +
     geom_text_repel(
         box.padding = 0.5,
         point.padding = 0.1,
         force = 5,
         nudge_x = 0.1,
         segment.color = "black"
     ) +
     labs(x = "bemerkung", y = "z", title = "Streudiagramm, das die Tiefenbeziehung von Tier-Skeletten darstellt.") +
     theme(axis.line = element_line(color = "black", linewidth = 0.5),
           plot.title = element_text(face = "bold"))

That is much better, but I would still like to tweak some things. I would like the points to be a touch larger for starters. I would also like to highlight the skeleton being referenced by making the point red and a different shape, a triangle, to the other points. When doing this ggplot will automatically place a legend to the right of the plot. I don’t however want this so will change the shape and colour of the ‘guides’ to “none”.

 ggplot(data = readfile, aes(x = bemerkung, y = z, label = bemerkung)) +
     geom_point(aes(shape = factor(bemerkung == 234), color = factor(bemerkung == 234)), size = 4) +
     scale_shape_manual(values = c("FALSE" = 16, "TRUE" = 17)) +
     scale_color_manual(values = c("FALSE" = "blue", "TRUE" = "red")) +
     geom_text_repel(
         box.padding = 0.5,
         point.padding = 0.1,
         force = 5,
         nudge_x = 0.1,
         segment.color = "black"
     ) +
     labs(x = "bemerkung", y = "z", title = "Streudiagramm, das die Tiefenbeziehung von Tier-Skeletten darstellt.") +
     theme(axis.line = element_line(color = "black", linewidth = 0.5),  
           plot.title = element_text(face = "bold")) +
     guides(shape = "none", color = "none")

Super! Now I want to change the labeling of the axes to show that my y axis is the height above sea level and my x axis is the Flächenzeichnung.

 ggplot(data = readfile, aes(x = bemerkung, y = z, label = bemerkung)) +
     geom_point(aes(shape = factor(bemerkung == 234), color = factor(bemerkung == 234)), size = 4) +
     scale_shape_manual(values = c("FALSE" = 16, "TRUE" = 17)) +
     scale_color_manual(values = c("FALSE" = "blue", "TRUE" = "red")) +
     geom_text_repel(
         box.padding = 0.5,
         point.padding = 0.1,
         force = 5,
         nudge_x = 0.1,
         segment.color = "black"
     ) +
     labs(x = "Flächenzeichnung", y = "Höhe über dem Meeresspiegel(m)", title = "Streudiagramm, das die Tiefenbeziehung von Tier-Skeletten darstellt.") +
     theme(axis.line = element_line(color = "black", linewidth = 0.5),  
           plot.title = element_text(face = "bold")) +
     guides(shape = "none", color = "none")

Dancer! Now I just need to make one of these for each Flächenzeichnung. But there are soooo many and I am really really lazy. So I should automate it. Which I do, like so!

 for (point in unique(readfile$bemerkung)) {
     point_data <- subset(readfile, bemerkung == point)
      +     plot <- ggplot(data = readfile, aes(x = bemerkung, y = z, label = bemerkung)) +
         geom_point(aes(shape = factor(bemerkung == point), color = factor(bemerkung == point)), size = 4) +
         scale_shape_manual(values = c("FALSE" = 16, "TRUE" = 17)) +
         scale_color_manual(values = c("FALSE" = "blue", "TRUE" = "red")) +
         geom_label_repel(
             data = readfile,
             aes(label = bemerkung),
             box.padding = 0.5,
             point.padding = 0.1,
             force = 5,
             nudge_x = 0.2,  # Adjust the horizontal positioning of the labels
             nudge_y = -0.2,  # Adjust the vertical positioning of the labels
             segment.color = "black",
             max.overlaps = Inf
         ) +
         labs(x = "Flächenzeichnung", y = "Höhe über dem Meeresspiegel(m)", title = "Streudiagramm, das die Tiefenbeziehung von Tier-Skeletten darstellt") +
         theme(axis.line = element_line(color = "black", linewidth = 0.5),  
               plot.title = element_text(face = "bold")) +
         guides(shape = "none", color = "none")
      +     ggsave(filename = paste0(point, ".png"), plot = plot, width = 9.02, height = 5.86, units = "in", path = "PATH_TO_THE_SAVE_FOLDER")
 }

The code above will iterate through the dataframe, our imported .csv, and create a scatterplot styled as above, with slightly nicer  labels, and save one plot per point in the defined folder.

TADA!

Right, now I can get on with making the full document for the local heritage folks. Unfortunately I can’t share that here as that will be containing actual sensitive archaeological data. Toodlepip!

 

Plotting Characters

  • pch = 1: ●
  • pch = 2: ⬟
  • pch = 3: ▲
  • pch = 4: ◆
  • pch = 5: ■
  • pch = 6: ▼
  • pch = 7: ►
  • pch = 8: ◄
  • pch = 9: A
  • pch = 10: B
  • pch = 11: ⬠
  • pch = 12: ⧊
  • pch = 13: ⊞
  • pch = 14: ⊠
  • pch = 15: ■ (square)
  • pch = 16: ● (circle)
  • pch = 17: ▲ (triangle)
  • pch = 18: ◆ (diamond)
  • pch = 19: ⬥
  • pch = 20: ⧇
  • pch = 21: ⧄
  • pch = 22: ⬝
  • pch = 23: ⬢
  • pch = 24: ⊏

 

 

*I was originally going to call this “Don’t have a cow man!”, but wanted to go for a slightly more obscure pop culture reference in order to highlight my nerd credentials. As though an article about using R to generate a scatterplot of archaeological features isn’t nerdy enough.

Posted on

Ostroer Schanze – 3D Model

Recently I have been looking at hill-top fortified enclosures in the eastern state of Saxony. I chose Saxony to look at as it is one of the states that puts a lot Geo-Data online for the public to freely access, just as it should be. I’m looking askance at you Niedersachsen… I’m interested in learning how to make 3D models of archaeological features in the landscape, carrying out viewshed analysis to see which features may or may not be related, and perhaps even predicting where as yet unidentified features may be found. To this end I downloaded the Lidar data from the website of the Landesamt für Geobasisinformation in Saxony and, after tweaking it a bit with CloudCompare, imported into QGIS in order to carry out a basic viewshed analysis and to create a 3D model which you can see below.

As you can hopefully see the hillfort, in the center of the image, has two sections with the section shaded green in the second image being the higher area. The fortification is bounded on the western side, to the left in the image, by the Klosterwasser, a small river, and a cliff of 21 meters. I don’t know for certain whetherthe western edge of the fortification had a wall though it could well be the case that it didn’t, given the natural protection from the steep western cliff. Although the wall could simply have collapsed at some point in the last two thousand years or so.

Profile of the western side of Ostroer Schanze

The viewshed looks out to the hills west of the fortification in order to see what parts of the landscape are viewable from the center of the higher area. My thinking here is that were the community going to build further monuments, with a mortuary or other ritual function, in the landscape they would do so somewhere that was visible from where they lived. I removed the satellite imagery that I had laid over my digital model and we can see that the Lidar scan has picked up subtle changes in the landscape within the viewshed. However there is nothing that looks like a monument. No telltale bumps or humps showing the remains of a mound or other structure within sight of the upper level of Ostroer Schanze.

Next I downloaded some orthographic photographs from the Landesamt für Geobasisinformation and laid them over my model to see if I could see any features.

Sadly not.

Oh well, better luck next time.