You can create a choropleth of US States with the function state_choropleth
:
library(choroplethr) ?df_pop_state data(df_pop_state) ?state_choropleth state_choropleth(df_pop_state)
As demonstrated above, the only required parameter to state_choropleth
is a data.frame. You can see the optional parameters by typing ?state_choropleth
.
The data.frame that you provide to state_choropleth
must have one column named “region” and one column named “value”. Your entries for “region” must exactly match how regions are named in the map which choroplethr uses. These names are defined in the object state.regions
:
library(choroplethrMaps) ?state.regions data(state.regions) head(state.regions)
region abb fips.numeric fips.character 1 alaska AK 2 02 2 alabama AL 1 01 3 arkansas AR 5 05 4 arizona AZ 4 04 5 california CA 6 06 6 colorado CO 8 08
In order to use choroplethr, you must use the naming convention in the “region” column of state.regions. That is, you must use full names in all lowercase letters.
The state_choropleth
function provides two parameters to facilitate exploring data: num_colors
and zoom
. num_colors
defaults to 7, which means that there are 7 colors on the map. An equal number of regions is assigned to each color; a value of 1 uses a continuous scale. zoom
defaults to NULL, which means that all states are shown. You can set it to be a vector of valid regions.
As an example, here is how you can use choroplethr to show the population of US States on the West Coast.
state_choropleth(df_pop_state, title = "2012 Population Estimates", legend = "Population", num_colors = 1, zoom = c("california", "washington", "oregon"))
Any customization outside the optional parameters presented above will require you to create a StateChoropleth
object. choroplethr uses R6 to take advantage of object-oriented programming. Here is an example of using the ggplot2_scale
variable on the base Choropleth object to customize the palette used.
This dataset is the 2012 US Presidential Election results. Normally in this map Democratic states appear blue and Republican states appear red.
library(ggplot2) ?df_president data(df_president) choro = StateChoropleth$new(df_president) choro$title = "2012 Election Results" choro$ggplot_scale = scale_fill_manual(name="Candidate", values=c("blue", "red"), drop=FALSE) choro$render()
For additional options on the StateChoropleth
object, such as removing the state labels, please see the choroplethr source code.
Note: Care must be taken when manually setting the scale on StateChoropleth
objects. In particular, choroplethr uses ggplot2 custom annotations to render Alaska and Hawaii as insets. This means that the scales of the insets and the main map will only be the same if you do the following
drop=FALSE
to the scale (as above).limits
which encompass the minimum and maximum values for the entire dataset.