cancel
Showing results for 
Search instead for 
Did you mean: 
intapiuser
Community Team Member
Community Team Member
Choropleths are fancy names for maps with heatmaps, probably because no one wants to say heatmap maps and feel redundant. In R there are packages that make Choropleth objects. choroplethr  holds the shape files, create a join of your data frame, and output with colors that you select as continuous or buckets of 2 - 9 categories. When I went to make a choroplethr object, I found that the base state_choropleth( ... ) function did not have the level of customization that I was looking for. Thankfully the package is well documented and I could go directly to the page for the StateChoropleth object and use it's methods to make further modifications!

The data frame that you pass into this should be the full state names and the attribute you want to use as the heatmap. My code renames the columns from "state_name" and "attribute" to the appropriate names for the StateChoropleth object.
library(ggplot2)
library(choroplethr)
library(choroplethrMaps)

df$state <- tolower(df$state_name)

plot_df <- data.frame("region" = df$state, "value" = df$attribute)

#Current Version of choroplethr does not include Hawaii or Alaska when ggplot_scale is used to override
#Add limits to the scale_fill_continuous to ensure generation of the appropriate scale
min_value = min(df$attribute, na.rm = TRUE)
max_value = max(df$attribute, na.rm = TRUE)

# Use more granular control by creating a StateChoropleth object
c = StateChoropleth$new(plot_df)
# Manually adjust the colors. Either a continuous or manual fill here
c$ggplot_scale = scale_fill_continuous(low="red",high="white",trans = 'reverse',na.value="black",limits=c(min_value, max_value))
# If the attribute is being passed as a categorical, the set_num_colors can be 2-9 for each bucket
c$set_num_colors(1)
# Optional zoom, can pass df$state to show only the selected states or NULL to return all
c$set_zoom(NULL)
# Optional to turn off the state labels because shapes do enough most of the time, TRUE is the default and a lot of text
c$show_labels = FALSE
# Create a call to render the object as p (for plot)
p = c$render()
# If you want to remove the legend, you can remove the comment for theme(legend.position = TRUE)
p # + theme(legend.position="none")

# uncomment the periscope.image() call below if using R in Periscope
# periscope.image()
Rate this article:
Version history
Last update:
‎03-02-2023 09:32 AM
Updated by:
Contributors