This particular custom legend was designed with three purposes:
- To effectively bin values based on a theoretical minimum and maximum value for that variable (e.g. -1 and 1 or 0 and 100)
- To use a different interval notation than the default
- To handle NA values
Even though this particular legend was designed with those needs, it should be simple to extrapolate from that to build legends based on other criteria.
Next we want to set some constants. This will save us a bunch of typing and will make the code easier to read, especially once we start creating a custom legend. Also, it will allow us to easily change the values if we want a different number of bins or a different min and max.
In this example, we’re assuming we have a theoretical minimum and maximum and want to determine our choropleth bins based on that.
And finally let’s add our default legend:
Here’s the output of this code (see map-standard-legend.R in the gist):
|Percent of power coming from coal sources (standard legend)|
Next we want to add a few lines here and there to enhance the legend.
For starters, let’s deal with NA values. We don’t have any in this particular dataset, but if we did, we would have seen they were left as the base color of the map and not included in the legend.
After our former code setting up the colors, we should add the color for NAs. It’s important that these lines go after all the other set up code, or the wrong colors will be mapped.
We also want to let the map know to have our NA color as the default color, so the map will use that instead of having those areas be transparent:
Next, we want to set up the legend text. For all but the last interval, we want it to say i ≤ n < (i + breaks). The last interval should be i ≤ n ≤ (i + breaks). This can be accomplished by
But we also want to include NAs in the legend, so we need to add a line:
And finally we need to add the legend to the map:
The new map (see map-new-legend.R) meets all the criteria we started with that the original legend didn’t have.
|Percent of power coming from coal sources (custom legend)|
Code is available in a gist.
Citations and Further Reading