Mapping with R Markdown
A natural extension of my last blog post about using R Markdown is to take it a step further and make maps with it. Â RMarkdown is a great tool to not only create the map, but to automate creating the map AND putting the map in a document.
This is a work-in-progress. Â This is a day late (I’ve been trying to keep to a Tuesday posting schedule to this blog, and well, it’s Wednesday afternoon when I’m finally typing this). I’m still not happily done, but I’m also ANGRY at the the output of the distribution model (now that I’ve changed a lot of stuff in the model), so I’m having to take a step back and redo friction factors, so rather than post a finished product, I decided to post the work in progress, which is probably as helpful as the finished product.
If you haven’t read last week’s post on using RMarkdown, do so now. Â I’ll wait. Â Back? Â Good.
The code:
The first part, above “Manually create the lines” is basic library-loading and data input (and some manipulation/subsetting)
The second part is creating the desire lines. Â These are created by first creating a list with two coordinate pairs in it (l1 – l7). Â Those objects are then created into individual lines (Sl1-Sl7). Â The individual lines are packaged into one Lines obeject (basically, a list of lines) (DL). Â Finally, that object is prepared for the map (deslines<-list…).
The third part is the text. Â There are two functions here, one is to get the mid-point of the line, the other is to get the angle of the line. Â There was a lot of trial and error that went into this. Â In the lines after the functions, the txt1-txt7 and mpt1-mpt7 objects, the text is formatted and map objects are created for them.
The fourth part is the counties for the map. Â The col=… and cpl<-… lines handle the colors for the counties.
The last part is drawing the map. Â The spplot() function handles all of that. Â The primary map is made out of the counties, and the lines and text is added in the sp.layout=… portion of the command.
That’s it! Â It really isn’t difficult as long as you remember trigonometry (and of course, you don’t even have to do that since it is in my code above. Â I also included some references at the bottom of the most useful resources when I was doing this, as there are many, many, MANY more ways to do this, options to play with, etc.
Example Report. Â NOTE: THE DATA IS INCORRECT.