Tuesday, 29 May 2018

Is deforestation resulting in rabies outbreaks in KZN?

Ever since I had to go for rabies treatment after being bitten by a bat under suspicious circumstances in Peru, rabies has held a certain fascination with me. A fruit bat had been reported in some-ones’ room in a jungle lodge where I was doing research. It was hanging on a bedside table, looking around and panting. I presumed it had been injured by staff clearing bats out of the ceiling, so I’d caught it in a pillow slip and walked it outside. I’d then attempted to release it gently to check for damage, but it scuttled out of the slip, turned around, sunk its teeth deep into my thumb, and then flew off: certainly not injured.

There had been some stories of gold miners who had died of rabies doing the rounds, so off it was to the local hospital. I’d like to joke that the week-long series of injections into my abdomen were worse than the disease: but that really isn’t the case here. Rabies is pretty much 100% fatal once symptoms display. I’ll never know if the treatment was for nothing, but I’d certainly not want to forego the treatment to find out.

This year, several people have died from bites by rabid dogs in South Africa, with several reports of rabid animals having to be put down. But how are these dogs getting rabies? The unwritten assumption of the reports is that there is low levels of rabies within dog and cat populations, but I find this rather unlikely: most cats and dogs die within 2 – 4 days of displaying symptoms, which is the only active transmission period. All cats and dogs die within 10 days. 

But what we do know is that bats can also carry rabies, and although they also die rapidly once symptoms show, it has also been show that rabies can hibernate with bats, so rabies is able to persist over seasons within bat colonies. In addition, there is good evidence that bats are hosts to other scary diseases like ebola.  

Now generally, bats are harmless creatures and carry on their lives rather independently of ours. They fly around, eating insects (which of course carry many more problematic diseases like malaria and yellow fever), pollinating flowers, dispersing fruit, and generally being very ecologically useful. That is, if their roosts and habitats are undisturbed. However, many bats roost in trees and utilise forests. So, if these are disturbed, then disrupted colonies will need to disperse, like refugees. These situations increase the risk of unwanted contact (from both species point of view) between bats and humans.

Over the last year or so there have been a number of stories, anecdotes and reports that are making me wonder if the deforestation in Kwazulu Nata (KZN) is associated with current rapid rates of deforestation. The rates of deforestation in South Africa are alarming by themselves: when I used to give talks comparing the amount of forest between South Africa and Peru, it was always 6% South Africa, 60% Peru. According to Global Forest Watch, who monitor deforestation and reforestation via satellite, South Africa is down to 3.5%. A lot of the forest loss has occurred over the last 15 years.

There are a lot of reasons for deforestation in South Africa, but one industry has popped up a couple of times on my radar independently.

Firstly, researchers at the University of KZN mentioned earlier this year that they had lost some of their indigenous forest study sites, where they were monitoring a range of species using camera traps, by farmers clearing land for macadamia nuts. Independently, a cousin of mine living in Port Edward spoke about a farmer who had lost his land in a land claim, but had been compensated, and then bought large tracts of unutilized land full of forest that he had cleared for macadamia nuts. By their own admission, the Macadamia nut association boasts of rapid growth in their industry. However, contribution to total forest loss is not quantified and may be small.

Certainly, at this stage I cannot say that the rabies is linked to deforestation, but there appears to be a smoking gun here that needs further investigation by South African authorities. At the moment, we may be treating a symptom, not the disease and human lives are at stake.

Thanks to Jamie Carr for assisting with the data for this post. 

Monday, 21 May 2018

Three week Wild West Karoo recce

A look of the atlas coverage map of South Africa has for years shown big unexplored areas in the heart of Bushmanland: that area south of the N14, between Upington and Springbok, and north of Louriesfontein. It is a sparsely populated area, with few protected areas to attract tourists and the associated birdwatching crowd. The big drawcard species to the area, the Red Lark, can most easily be seen close to the N14 at Aggenys, so there is little reason to venture into the vast hinterland of South Africa. That would include me: the last time I was in the area was in 2006 on a road trip to show off the wonders of the country to my German fiancé. But now, tasked with the daunting conservation assessment of our Karoo bird species, it was imperative that I familiarize myself more intimately with the region and its species.

I knew I would be away for the 3 weeks, so felt it was important to get some quality time in with the kids, and give the wife a short respite since parenting duties would be all hers for the interim. So I left home on Monday the 30 April, first on a family trip. We’d planned to head out earlier, but Eli had a bad cough and we decided to cut short our stay at Nature’s Valley campsite. The hikes through the forests, fynbos and along the beaches were refreshing, albeit evenings a bit chilly and the campfire much needed.

Too soon we were all back in Uniondale. And that was the start of the long road trip. Wednesday was a drive to the Overberg, to the Haarwegskloof Renosterveld Reserve , in order to give some moral support to Celeste de Kock doing point counts to determine distribution and density of Agulhas Long-billed Lark. Then Thursday the drive into Cape Town, with meetings all day on the Friday (at SANBI to touch base with Gigi Laidler of Karoo BioGaps, as well as Dale Wright, and at the Fitz to meet Rob Thompson, Rob Little, Res Altwegg and Dominic Henry). Dominic gave an impressive display of distribution maps using occupancy modelling which are the results of the point counts from the southern Karoo. It was really cool to see the efforts of last year being used to fill the information gaps for this under surveyed Karoo region.

Agulhas Long-billed Lark

A big reason for the trip to Cape Town was to give a bird course on Fynbos birds to the Cape Bird Club and share lessons learnt from 5 years of postdoctoral research on the topic. That was a bit of a rough ride: I was now in the grips of the flu/cough thing Eli had, and I was staying at a Backpackers, where I spent a near sleepless night on the Friday. Then on the Saturday, there were all sorts of technical issues with the presentation setup (mics not working and having to run off-stage in order to change slides and presentations). Luckily, the audience was sympathetic and patient. The afternoon was just a long nap and some bird watching to chill out, and a much needed early night and looooonnng sleep.

... the wildest Dragon Child, flames shooting from its head. (Antjie Krog, Fynbos Fairies). It might be planes in this case though.

Sunday was an early start to meet Susie Cunningham to work over a manuscript that needed fixing for resubmission, followed by a quick social visit to old friends. Then the drive to Hopefield to pick up Eric Herrmann, field assistant for the next couple of weeks recce trip across the western Karoo.

Our first night took us to the Botuin Guest house in Vanrhynsdorp, run by Salome Wilemse, of the Namaqua Bird Club. It was so nice we had to make some excuses to spend a second night there. After all, Vanrhynsdorp is gateway to the alluring Knersvlakte and a trip up the Vanrhyn's Pass takes one from Succulent Karoo to Fynbos in less than an hour. Salome was a fantastic guide, showing me some pentads with representative birdlife for the area. One of the pentads included a farm where an old friendly farmer, Willem van Zyl was struggling to make a living with the ongoing drought in the region. He boasts that he has the oldest Wild Olive tree on his farm: a massive tree that was apparently already huge when his father was a child, going back 100 years.

On the Tuesday we had to move on. Eric and I surveyed a potential pentad on the foothills of the Vanrhyns pass, which included the ‘Bagdad CafĂ©’ – certainly useful for the mid-morning cup of coffee. The pentad includes some of the famous Knersvlakte, the quartz gravel plains which hide a multitude of endemic succulents.

For our lunch stop we decided to drop in at the Oorlogspoort Nature Reserve, on the escarpment. The fynbos made a nice break from barren Karoo plains. Oorlogspoort has a series of overnight hikes, but being the wrong biome, unfortunately this could not be a study site. The reserve entrance was manned only by baboons, making me wonder about control and access to this bastion of biodiversity.

We had an afternoon rendezvous with Francois vd Merwe to make, a farmer just outside Calvinia.  Francois has a long history with the FitzPatrick Institute, and was very welcoming and supportive, suggesting a multitude of sites for exploration, as well as organising us accommodation in the Boekhuis ‘writer’s retreat’ in Calvinia. This would make an excellent base for exploring virgin pentads to the southeast, on farms overlooking the Tankwa Karoo. We were a bit concerned our 2x4 would not make the Bobbejaanspas, but the track proved to be in good condition. I couldn’t resist mounting up the mountain bike for a bit of adrenalin pumping downhill, with Eric taking the more cautious drive down. At the end of the day, a long round trip saw us submitting the first full protocol lists for two pentads, as well as several ad-hoc lists.

Our next destination was a farm that is now the site of a wind farm north of Loeriesfontein. After the necessary induction to access the wind turbine areas, we spent the afternoon on an exploration of some old farm tracks, which turned up the first Red Lark of the trip. We camped near an abandoned farm-house, with views of the Sishen train line. To kill some time we decided to count the carriages on one of the trains, getting to over 300 before getting bored.

Red Lark choosing the most uncomfortable perch

Red Lark aerial display

The next morning we were up and packed early, as we’d noticed that the area south of Pofadder was full of unsurveyed pentads. Eric cycled through two of these, while I drove further north and did another two. Unlike the areas to the south, this part of Bushmanland had received good summer rains: the grass was tall and water filled the normally dry, salty pans. Lark-like Buntings, Grey-backed Finchlarks and even Stark’s Lark were abundant. Red Lark were recorded in all four pentads. While we’d been thinking of doing more in the afternoon, a very strong westerly wind picked up, sending the birds for cover. We pushed on to Pofadder, where we rendezvoused with Pieter Jan. He has a contact from a neighbour of mine, his mother having grown up in the area I now live, Hartbeesrivier.

Stark's Lark among the summer flush of green - the first in four years

For camping we headed for Klein Pella, a date farm that also has accommodation, close to the Orange River, the granite mountains that wind west to form part of the Richtersveld. The area was looking rather beautiful, with grass, flowers, and myriads of nomadic birds. We’d planned to scout Pieter Jan’s farm early the next day, but got side-tracked with the birds at Klein Pella, with Eric and I clocking close to 50 birds each in our 2.5 hours. This time I had the bike, and enjoyed an amazing ride down to the Orange River. I’ll say I wasn’t too sad when later that morning Eric, who was worried I’d not made it back to camp (due to the birdlife), decided to head down to see if I was in trouble.

After scouting the target pentad, which had the usual flocks of nomadics, we headed down the road to Springbok and the campsite just outside town. The Goegap Nature Reserve nearby provided rewarding birds and promises to be a fun survey site come July/August: although apparently we’ll need to book well in advance as the place is packed come Namaqualand flower season.

From Springbok the road to Port Nolloth provided another survey opportunity, with a community accommodation option just at the top of the Anenous pass. The pass proved to be another irresistible down-hill biking opportunity, although I got sidetracked at the bottom by some Karoo Larks. Of course this is the start of Barlow’s Lark country on the map. However, good sightings left us pretty confident that the pass is still firmly Karoo Lark country.

At the museum at Port Nolloth, it was interesting to learn of some previous monitoring of Barlow’s Lark nest sites just outside of town. However, what became of that research, the curator’s daughter did not seem to know. Eric scouted the town pentad, coming up with several Cape Long-billed Lark groups, as well as Red-capped Lark and Capped Wheatear foraging on the kelp covered beaches. No Barlow’s Lark though.

So, Monday morning we headed north on the road to Alexander Bay. Thick fog kept us pushing far along the road, until 30km south of Alexander Bay we decided to follow a track that ran off the main road, but down the mining fence, in beautiful Succulent Karoo veld, resembling an underwater coral field. Here finally, the rattle call of what could have been a Karoo Lark revealed birds with plain, unstreaked flanks: Barlow’s Lark! A little later on, with the assistance of some playback of Eastern Long-billed Lark, a Cape Long-billed Lark responded beautifully, allowing great views and a few photo opportunities of this really long-billed beauty. Apparently it is not just to human ears that these calls are so similar.

That afternoon we explored a targeted pentad south of the Richtersveld region. Although only 15 km or so inland from Barlow’s Lark range, the sands here are red, rather than beachy-white, and we were back into Karoo Lark territory, with birds reddish and typically streaky. Amazing how quickly the forms of birds transition in this area.

Tuesday was an exploration of the back routes to the Namaqua National Park. A highlight of the morning was summoning another Cape Long-billed Lark with the call of Eastern Long-billed Lark, although I failed to get a much desired photo of this pale bird against striking Namib red sands.

Our entry into the Namaqua National Park would be described as confusing as best. The northern boundary (clearly obvious due to the presence of a tortoise-killing electric fence that spans this and many other SANParks reserves) is not manned, with no directions to any reception of any kind. Ironically, the parks signature campsite on the eastern boundary is called Skilpad (Tortoise). We eventually found the reception here, after spending a day revelling in the scenery of the hills that lead to Kamieskroon. While the park does not itself offer camping at the Skilpad reception gate, there is camping offered by Skilpad Farm immediately adjacent.

Eric and I spent what was left of the afternoon walking the ‘Korhaan Trail’ practising point count methodology. No Korhaan though. And that was a wrap: the next morning I set out for Kamieskroon on the bike, Eric picked me up along the road, and drove us all the way back to Hopefield. I had a few more hours on the road to get to Cape Town, where I was kindly hosted by Dale and Este Wright. Thursday was an action packed Fitz AGM, and Friday the long ride home.

Some further images from the trip:

Molting Malachite Sunbird: birds at Blue Hill are in mixed eclipse plumage in May

Karoo Scrub Robin

Confused Kudu / Curious Cow

Karoo Eremomela

Sickle-winged Chat

A Hantam Karoo Karoo Lark

Thick-billed Lark seeks shade in the Tankwa

Capped Wheatear

Female Southern Red Bishop

Lark-like Bunting drinking precariously from inside a reservoir

Karoo Long-billed Lark

Non-breeding male Southern Red Bishop

Tankwa geophyte

Rumours that I am short are greatly exaggerated

Eric heads out atlasing on the bicycle

Kokerboom Forest near Klein Pella

Another ridge top glory shot

Lizard and Stapelia

Rough roads: the front grill shook loose at Alexander Bay

Making the most of the sun to dry fog drenched tents at Port Nolloth

On the road to Namaqualand

Monday, 16 April 2018

SABAP2 The Movie maps in R

SABAP2 'The Movie' maps in R

Professor Les Underhill's vision for SABAP2 would be that it would continue to collect data in perpetuity in order to examine patterns in space and time: SABAP2 The Movie.

Now, with 10 years of data and counting, we can create these movies. There are many stories that wait to be told.

The existing SABAP2 map is static: it is the result of compounded lists across the 10 year history. This hides any dynamic patterns. The first and most obvious is seasonality, especially for migratory species. First, we will look at the monthly occurrence of a migratory species, building on what we did here:

# These are the packages required to run these scripts
library(ggplot2); library(dplyr); library(gganimate); library(animation) 
# gganimate is still only available via GitHub at this stage: https://github.com/dgrtwo/gganimate

# You will need to download and install the free image processing software ImageMagick: 
# https://www.imagemagick.org/script/download.php

# Tell R where ImageMagick lives:
magickPath = shortPathName("C:\\Program Files\\ImageMagick-7.0.7-Q16\\magick.exe") 

# Download your data here by replacing the 493 here with the species code of your choice (or pasting the link)
swallow =
  read.csv("http://sabap2.adu.org.za/inc/species_data_download.php?spp=493&section=6", stringsAsFactors = F)

# restrict the data to southern Africa (the region with the best coverage)
swallow = filter(swallow, lat<(-15))

# add reporting rate
 swallow$reporting_rate = swallow$cards_with_spp/swallow$cards

The new code starts here. First, we use the raw data to create a background map of where we have bird lists (coverage) using the atlas data. We then create a new dataframe of average reporting rate by month. Finally, we plot the black coverage map and overlay reporting rate (on a gradient from black with nothing, to red i.e. high reporting rate). Pentad size here is proportionally larger than in reality, which helps fill in atlasing holes. This is a movie after all, not an analysis.

#first, background pentad map
pentad_map_data = swallow%>%select(pentad, lat, lng)%>%distinct()

# now dataframe for mapping
annual_pattern = swallow%>%group_by(mnth, lng, lat)%>%summarise(rr=mean(reporting_rate))%>filter(rr>0)

swallow_space_time =
    ggplot(pentad_map_data, aes(lng, lat))+
      geom_point(shape=15)+ylim(min(swallow$lat), -15)+xlim(min(swallow$lng), 37)+
      theme_bw(base_size = 15)+coord_equal()+xlab("Longitude")+ylab("Latitude")+

      geom_point(data=annual_pattern, aes(lng,lat, colour=rr, frame=mnth),shape=15)+
      scale_colour_gradient(low="black", high="#de2d26", guide="none")+
      ggtitle("Spatial distribution of Barn Swallow for month ")

 suppressMessages(gganimate(swallow_space_time, interval=1))

A static map is also not appropriate if a species is nomadic: range will change from year to year depending on rainfall and resources. This is especially the case for several species of the arid zone. One of the most common and familiar is the Lark-like Bunting Emberiza impetuani. Here we examine year by year reporting rate for this species, revealing a remarkeably dynamic range (as you will see when we compare this to an endemic bird species below). SABAP2 data reveals an extraordinary irruption of Lark-like Bunting in 2013 that went largely unmentioned in South Africa's ornithological literature.

# get the data:
llbunting =
  read.csv("http://sabap2.adu.org.za/inc/species_data_download.php?spp=871&section=6", stringsAsFactors = F)

llbunting = filter(llbunting, !yrr%in%c(2007, 2018))
llbunting$reporting_rate = llbunting$cards_with_spp/llbunting$cards
annual_pattern = llbunting%>%group_by(yrr, lng, lat)%>%

# now a spatial map

llbunting_space_time =
    ggplot(pentad_map_data, aes(lng, lat))+
    geom_point(shape=15)+ylim(min(llbunting$lat), -15)+xlim(min(llbunting$lng), 37)+
    theme_bw(base_size = 15)+coord_equal()+xlab("Longitude")+ylab("Latitude")+

    geom_point(data=annual_pattern, aes(lng,lat, colour=rr, frame=yrr),shape=15)+
    scale_colour_gradient(low="black", high="#de2d26", guide="none")+
    ggtitle("Spatial distribution of Lark-like bunting for year ")

suppressMessages(gganimate(llbunting_space_time, interval=2))

By comparison, the 'movie' for Cape Sugarbird is far less interesting, with the exception of perhaps of the odd individual wondering out of range.

# get the data:
csb =
  read.csv("http://sabap2.adu.org.za/inc/species_data_download.php?spp=749&section=6", stringsAsFactors = F)

csb = filter(csb, !yrr%in%c(2007, 2018))
csb$reporting_rate = csb$cards_with_spp/csb$cards
annual_pattern = csb%>%group_by(yrr, lng, lat)%>%
# now an animated spatial map csb_space_time = ( ggplot(pentad_map_data, aes(lng, lat))+ geom_point(shape=15)+ylim(min(csb$lat), -15)+xlim(min(csb$lng), 37)+ theme_bw(base_size = 15)+coord_equal()+xlab("Longitude")+ylab("Latitude")+ geom_point(data=annual_pattern, aes(lng,lat, colour=rr, frame=yrr),shape=15)+ scale_colour_gradient(low="black", high="#de2d26", guide="none")+
ggtitle("Spatial distribution of Cape Sugarbird for year ")

suppressMessages(gganimate(csb_space_time, interval=2))

And finally, we watch the spread of atlasing coverage over the last decade, coupled with the presence of Pied Crow. This chart is a cumulative one: each year laid over the previous.

pied_crow =   read.csv("http://sabap2.adu.org.za/inc/species_data_download.php?spp=522&section=6", stringsAsFactors = F)

pied_crow$rr = with(pied_crow, (cards_with_spp/cards))

annual_pattern = pied_crow%>%group_by(yrr, lng, lat)%>%summarise(rr=mean(rr))

pied_crow_space_time = 
      ylim(min(pied_crow$lat), -15)+xlim(min(pied_crow$lng), 37)+
      geom_point(data=annual_pattern, aes(lng,lat, colour=rr, frame=yrr, cumulative=T),shape=15)+

      theme_bw(base_size = 15)+coord_equal()+xlab("Longitude")+ylab("Latitude")+

      scale_colour_gradient(low="black", high="#de2d26")+
ggtitle("Coverage and Pied Crow CUMULATIVE year ")

gganimate(pied_crow_space_time, interval = 1)

Illustrating inter-annual trends of SABAP2 reporting rate in R

Illustrating inter-annual trends of SABAP2 reporting rate in R

In my last post we learnt how to animate annual trends in monthly reporting rate. But was there any change in overall reporting rate across years?


So how is reporting rate changing between years for Barn Swallow Hirundo rustica. We can't really tell from the species summary page:


For this exercise you will need the data at the link marked “Pentad level summary (monthly)” under the Data downloads options.

For the animated chart you will need to download and install the free image processing software ImageMagick: https://www.imagemagick.org/script/download.php

# These are the packages required to run these scripts
library(ggplot2); library(dplyr); library(gganimate); library(animation) 

# Tell R where ImageMagick lives:
magickPath <- ani.options="" code="" convert="magickPath)" files="" magemagick-7.0.7-q16="" magick.exe="" rogram="" shortpathname="">

Here we prepare the data (for explanation of these steps see previous post). I've included this so the code can run as a stand-along script.

# Download your data here by replacing the 493 here with the species code of your choice (or pasting the link)
swallow <- africa="" best="" coverage="" data="" filter="" group_by="" http:="" inc="" lat="" occurrence="" of="" pentad="" range="" read.csv="" region="" restrict="" sabap2.adu.org.za="" southern="" species="" species_data_download.php="" spp="493&section=6" stringsasfactors="F)" swallow="" the="" to="" with="">%

occurrence <- add="" amp="" cards="" cards_with_spp="" code="" filter="" occurrence="" ok="" rate="" reporting="" reporting_rate="" swallow="">

The new code starts here. First, it is a good idea to remove data from 2007 (and maybe even 2008). 2007 is the year SABAP2 got going: submission rates and spatial coverage were low. Also remove the current year.

# exclude unwanted years:
swallow <- 2018="" a="" and="" by="" c="" error="" filter="" group_by="" here="" in="" include="" measure="" now:="" of="" rate="" reporting="" standard="" summarise="" summary="" swallow="" year="" yrr="">%
summarise(mean=mean(reporting_rate), sd=sd(reporting_rate), n=sum(cards_with_spp), se=sd/sqrt(n))

chart_title = c("SABAP2 reporting rate trend for \n Barn Swallow")

p <- 2018="" aes="" base_size="14)+" chart="" code="" coord_cartesian="" cumulative="T))+geom_bar(stat=" ear="" eporting="" frame="yrr," geom_errorbar="" ggplot="" identity="" is="" labs="" mean="" p="" proportion="" rate="" static="" summary="" the="" theme_bw="" this="" title="chart_title)+" xlab="" xlim="c(2007," ylab="" ymax="mean+se))" ymin="mean-se," yrr="">

# Here I add a regression line across the interannual mean reporting rate values
q = p+
geom_smooth(data=summary, aes(yrr, mean),   method="lm", color="red")


# The animated version  
gganimate(q, interval = .5)

# Save the above as gif: suppressMessages(gganimate(q, interval=6, "SWALLOW_barchart_time_series.gif"))

# A simple linear regression suggests no significant change. 
# Obviously real life may be much more complicated than this suggests.   

summary(lm(mean~yrr, data=summary))
## Call:
## lm(formula = mean ~ yrr, data = summary)
## Residuals:
##       Min        1Q    Median        3Q       Max 
## -0.042814 -0.015509  0.005625  0.024023  0.025913 
## Coefficients:
##              Estimate Std. Error t value Pr(>|t|)
## (Intercept)  8.854237   6.314515   1.402    0.198
## yrr         -0.004226   0.003138  -1.347    0.215
## Residual standard error: 0.0285 on 8 degrees of freedom
## Multiple R-squared:  0.1848, Adjusted R-squared:  0.08293 
## F-statistic: 1.814 on 1 and 8 DF,  p-value: 0.215

##  Try a more statistically robust approach to interannual change in reporting rate
## using a clt / bootstrapping approach with random samples

#initialise the target dataframe:

df = data.frame(year=2007, rr=NA)

# Run a loop that selects each year, removes sites with low sampling effort, 
# and then subsamples a random set of the available data 1000 times

for(i in 2008:2017){
  temp = filter(swallow, yrr==i&cards>2)%>%select(reporting_rate)
  holder = rep(NA, 1000)

    for(b in 1:1000){
    temp2 = sample(temp$reporting_rate, 100, replace = F)
    holder[b] = mean(temp2)

  holder2 = data.frame(year=i, rr=holder)
  df = rbind(df, holder2)

df = filter(df, year!=2007)

# plot it:

ggplot(df, aes(year, rr))+
  geom_smooth(method="lm", colour="red")+

Friday, 13 April 2018

Animated SABAP2 reporting rate timelines

Making animated monthly reporting rate charts from SABAP2 public data in R

Currently you can get a lot of information from the SABAP2 website. For example, go here to find information on Barn Swallow Hirundo rustica.


The aim of this post is to animate the current static monthly reporting rate chart to the right of the map. As there are now many years of data, it is hard to understand what is going on in the static chart now.

For this exercise you will need the data at the link marked “Pentad level summary (monthly)” under the Data downloads options. Note this file is fairly large (8 Mb), so download can take a minute or two, depending on your bandwidth.

You will need to download and install the free image processing software ImageMagick: https://www.imagemagick.org/script/download.php

In addition gganimate is currently only available on github

# These are the packages required to run these scripts
library(ggplot2); library(dplyr); library(gganimate); library(animation) 

# For me (but maybe not for you), I need to tell R where ImageMagick lives:
magickPath <- shortPathName("C:\\Program Files\\ImageMagick-7.0.7-Q16\\magick.exe") 
#update your path as necessary
# Download your data here by replacing the 493 here with the species code of your choice (or pasting the link)
swallow <- read.csv("http://sabap2.adu.org.za/inc/species_data_download.php?spp=493&section=6", stringsAsFactors = F)

Have you got the data?

Here is a quick chart to make sure you have the data, a histogram of the number of full protocol cards submitted by year


Since SABAP2 now extends into Africa on a fairly ad-hoc basis, you may wish to restrict your analysis to the southern African region by running swallow <- filter(swallow, lat<(-15)).
Most of the atlased area (currently in your data frame) may well be outside the range of the species, especially if you are dealing with a range-restricted or endemic species. If we use all data, then we will have very low reporting rates. This is likely not what you want: you want to know reporting rate from within a species range. So this step restricts the dataset to the set of pentads where the species has ever been recorded.

occurrence <- group_by(swallow, pentad) %>%

# now get rid of pentads with ok ==0 i.e non occurrence. 
occurrence <- filter(occurrence, ok!=0) 
Unlike some of the data sets available for download, this one does not come with reporting rate. So we need to calculate that. It will be a proportion (between 0 and 1).

 swallow$reporting_rate <- swallow$cards_with_spp/swallow$cards
#lots of 0 and 1: artefacts of coverage where pentads surveyed only once can only be 0 or 1

This is something like what the chart on the SABAP2 website currently looks like:

ggplot(data = group_by(swallow, yrr,mnth)%>%
  , aes(mnth, mean_reporting_rate,colour=factor(yrr)))+geom_line()

So lets animate that.

# we need a time series value that combines year and month

swallow$yrr_mnth <- swallow$yrr+round(swallow$mnth/100, 2)

# Now create the chart
p <- ggplot(data = group_by(swallow, yrr, mnth, yrr_mnth)%>%
    filter(pentad%in%occurrence$pentad  & yrr%in%c(2009, 2012, 2015, 2017))%>% # displaying only a few years for clarity
  aes(mnth, mean_reporting_rate,colour=factor(yrr), frame=yrr_mnth,cumulative=T, size=yrr/2009))+
  geom_path(alpha=0.5)+ggtitle("Monthly reporting rates for Barn Swallow for ") +
  theme_bw(base_size = 14)

# Display the animated plot. Interval controls the speed. 
suppressMessages(gganimate(p, interval=0.5))
If you want to save the chart as a gif file run this. Various other formats exist: check the animation package documentation.

suppressMessages(gganimate(p, interval=0.5, "barn_swallow_time_series.gif"))
Related Posts Plugin for WordPress, Blogger...