<jupyter_start><jupyter_text>Creating Choropleth Map using Choroplethr via rpy2 This is a jupyter notebook that explains how to make a choropleth map using R's choroplethr package from within Python via rpy2 interface.  rpy2 is a Python package that allows you to run R code from within Python.  Why am I doing this?  Currently, there isn't a library or package in Python world that makes choropleth maps as easily as R's choroplethr package.  A choropleth map is a geographical visualization map in which the intensity of the colored shaded regions corresponds to a metric or measurement.In this example, I will be generating a choropleth map representing unemployment rates by US counties.  The data can be obtained [here](http://www.bls.gov/lau/tables) in the "COUNTY DATA" section.  The raw data that I am working with is [here](http://www.bls.gov/lau/laucntycur14.txt).If you look at the raw data, you can see that I need to ignore or skip the first 6 rows of data which means I will have to make my own set of column names.  The column data is separated or delimited by a "|" character.  Reading the code below, you should be able to guess what it does:<jupyter_code>import pandas as pd

df = pd.read_csv('http://www.bls.gov/lau/laucntycur14.txt', header=None, skiprows=6, sep='|',
                names=['LAUS','FIPS_STATE','FIPS_COUNTY','AREA_TITLE','PERIOD','CIV_LABOR_FORCE','EMPLOYED',
                       'UNEMPL_LEVEL','UNEMPL_RATE'],
                dtype={'FIPS_STATE':str, 'FIPS_COUNTY':str})
df.head()<jupyter_output><empty_output><jupyter_text>Per choroplethr [documentation](http://cran.r-project.org/web/packages/choroplethr/vignettes/c-county-choropleth.html) under "Data Requirements", we need to create a "region" column which is the FIPS state code and FIPS county code meshed together.  But first, we need to remove leading and trailing whitespaces and leading zeros.<jupyter_code>df['FIPS_STATE'] = df['FIPS_STATE'].str.strip()         # remove/strip leading or trailing whitespaces
df['FIPS_STATE'] = df['FIPS_STATE'].str.lstrip('0')     # left strip / remove leading zeros
df['FIPS_COUNTY'] = df['FIPS_COUNTY'].str.strip()
df['region'] = df.FIPS_STATE + df.FIPS_COUNTY           # concatenate or mesh together the state and county FIPS code
df['value'] = df['UNEMPL_RATE']                         # create a column called "value" containing unemployment rates
df.head()                                               # Let's see what the first 5 rows of our data looks like<jupyter_output><empty_output><jupyter_text>The description of the data set from the web site says it has data from Mar'13 through Apr'15:<jupyter_code>df.PERIOD.value_counts()<jupyter_output><empty_output><jupyter_text>We can see from above that for each time period, there are 3,219 rows of data, with the exception of "Apr-15" data.  Let's just obtain the most recent data and we also need to exclude Puerto Rico which has a FIPS code of 72<jupyter_code>criteria1 = df['PERIOD'].str.contains('Mar-15', na=False)
criteria2 = df['FIPS_STATE'] != '72'
recent = df[criteria1 & criteria2]<jupyter_output><empty_output><jupyter_text>Let's double-check if our data only has Mar'15 data<jupyter_code>recent.head()
recent.PERIOD.value_counts()<jupyter_output><empty_output><jupyter_text>Alright, so our data set consists of just Mar'15 data and contains 3,141 rows  Our choropleth data doesn't need all those columns, so we'll just grab the ones that matter<jupyter_code>choropleth_data = recent[['region','value','AREA_TITLE']]
choropleth_data.head()<jupyter_output><empty_output><jupyter_text>Load the rpy2 extension so that we can execute R code from within Python<jupyter_code># load the rpy2 extension
%load_ext rpy2.ipython<jupyter_output><empty_output><jupyter_text>Send the choropleth_data to the R environment<jupyter_code>%R -i choropleth_data<jupyter_output><empty_output><jupyter_text>Now load the choropleth package, convert the Python data frame to R data frame and make the county choropleth map<jupyter_code>%%R -w 800 -h 500 -u px
library(choroplethr)
choropleth_data = as.data.frame(choropleth_data)
county_choropleth(choropleth_data)<jupyter_output>Error in eval(expr, envir, enclos) : 
  cannot join on columns 'region' x 'region': Can't join on 'region' x 'region' because of incompatible types (factor / numeric)<jupyter_text>Error message above is telling us that it doesn't like that one of our columns is a "factor" data type.  Not sure why R wasn't smart enough to import the columns to the proper data type.  But anyways, I'll convert the region column as numeric type:<jupyter_code>%%R -w 800 -h 500 -u px
library(choroplethr)
choropleth_data = as.data.frame(choropleth_data)
choropleth_data$value = as.numeric(as.character(choropleth_data$value))
county_choropleth(choropleth_data, title = "Unemployment Rate by US Counties (March 2015)",
                 legend = "Unemployment Rate")<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.08986035215543413, 'fraction_numerical': 0.011738514470754908, 'mean_word_length': 4.90442054958184, 'pattern_counts': {'":': 0, '<': 40, '<?xml version=': 0, '>': 40, 'https://': 0, 'lorem ipsum': 0, 'www.': 3, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 2, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '10', 'dir': 'jupyter-structured-clean-dedup', 'id': '165119', 'license': 'MIT', 'n_tokens_mistral': 1616, 'n_tokens_neox': 1520, 'n_words': 544, 'path': 'jupyter_notebooks/rpy2/County_Choropleth_Map_Using_Choroplethr_rpy2.ipynb', 'repo_name': 'manual123/Nacho-Jupyter-Notebooks', 'size': '4941'}