*! version 1.0.5 22june2017

Title

maptile -- Categorical maps

Syntax

Map a variable

maptile
varname [if] [in],
geography(geoname) [options]

Helper programs:
maptile_install,
maptile_geolist,
maptile_geohelp

options

Main
geography(geoname) geographic template to map

geo_options options specific to the geographic template being used

twopt(twoway_options) pass twoway graph options to graph command

Bins
nquantiles(#) number of quantiles (color bins); default is 6

cutpoints(varname) use values of varname as cutpoints

cutvalues(numlist) use values of numlist as cutpoints

Colors
revcolor reverse color order

propcolor space colors proportionally to the data

shrinkcolorscale(#) shrink color spectrum to fraction of full size; default is 1

rangecolor(colorstyle colorstyle) manually specify color spectrum boundaries

fcolor(spmap_colorlist) manually specify color scheme, instead of using a color spectrum

ndfcolor(colorstyle) color for areas with missing data

Legend
legdecimals(#) number of decimals to display in legend

legformat(%fmt) numerical format to display in legend

Output
savegraph(filename) save map to file; format automatically detected from file extension

replace overwrite the file if it already exists

resolution(#) scale the saved map image by a proportion; default is 1

Advanced
mapif(condition) restrict the map to a subset of areas

spopt(spmap_options) pass spmap options to graph command

geofolder(folder_name) folder containing maptile geographies; default is PERSONAL/maptile_geographies

hasdatabase dataset already contains the polygon idvar

Description

maptile makes it easy to map a variable in Stata. It generates choropleth maps, where each area is shaded according to the value of the variable being plotted.
By default, maptile divides the geographic units into equal-sized bins (corresponding to quantiles of the plotted variable), then colors the bins in increasing intensity.

To generate any particular map, maptile uses a geography, which is a template for that map.
These need to be downloaded and installed. If no geography currently exists for the region you want to map, you can create a new one.

maptile requires spmap to be installed, and is largely a convenient interface for using spmap.
As its help file states, "spmap gives the user full control over the formatting of almost every map element, thus allowing the production of highly customized maps".
When using maptile, most of these customizations are stored away in the geography template.
As a result, the syntax for making highly customized maps using maptile can be very simple.
Additionally, the geography templates can be easily shared and used by others.

Installing geographies

maptile geography templates are distributed as .ZIP files. Many are available from maptile's website.

1) To install a new geography template automatically, use:

maptile_install using URL|filename [, replace]

When you point maptile_install to a URL or local ZIP file, it will automatically extract the files to the PERSONAL/maptile_geographies folder. That is where maptile looks for geography templates by default.

If you add replace, it will automatically overwrite existing files with ones from the ZIP file.

2) Alternatively, you can install a geography manually.

Simply extract the geography ZIP file to any folder on your computer.
Then direct maptile to look in that folder using the geofolder(folder_name) option.

Using geographies

1) Specify the geography name (geoname)

Each time you run maptile you need to specify the name of a geography template to use with the option geography(geoname).

To list the names of currently installed geographies, use:

maptile_geolist [, geofolder(folder_name)]

Running maptile_geolist without any options will list geographies in the PERSONAL/maptile_geographies folder, which is where maptile loads geographies from automatically.

2) Ensure your dataset contains the correct geographic ID variable

Your dataset must contain a geographic identifier variable, which associates each observation with an area on the map.

Each geography will expect a specific geographic ID variable. For example, the geography for U.S. states might require a variable named "state" containing 2-letter state abbreviations.
The required geographic ID variable will be indicated in the geography's help file.

To see a geography's help file, use:

maptile_geohelp geoname [, geofolder(folder_name)]

3) Use any geography-specific options desired (geo_options)

Some geographies provide additional options which you can add to the maptile command.

For example, a geography may provide an option that lets the user choose among a variety of geographic ID variables.
As another example, some geographies of the United States provide an option to place a heavier line on state borders.

These additional options will be detailed in the geography's help file.

Making new geographies

Instructions are provided here.

Options

Main

geography(geoname) specifies the name of the geography template that maptile will use to create the map.
The geography template must be installed on your computer.
Your dataset must contain the correct geographic ID variable for the specified geography template.

geo_options:

Some geographies provide additional options which you can add to the maptile command.
These additional options will be described in the geography's help file.

twopt(twoway_options) passes twoway options through to the graph command.
These can be used to control the graph titles,
legends, etc.
See Example 3 ("Formatting") for some demonstrations.

twoway options are supported by all twoway graphs, and are typically added directly to the command generating the graph.
But with maptile all twoway options must be enclosed within twopt().

Other formatting options are available through spmap using spopt(spmap_options) [jump down].
Note that technically all twoway options are passed to spmap, so enclosing them in spopt() is equivalent to enclosing them in twopt().

Bins

nquantiles(#) specifies the number of equal-sized color bins to be created.
The default is 6. The bins created match the results of xtile.
This option cannot be combined with cutpoints() or cutvalues().

It is possible that fewer bins are created than specified, for example if the variable being mapped takes fewer unique values than the number of bins requested.
For more information, see the technical note on non-unique quantiles in the [D] pctile manual.

cutpoints(varname) causes maptile to use the values of varname as cutpoints for the color bins.
All values of varname are used, regardless of any if or in restriction.
This option cannot be combined with nquantiles() or cutvalues().

This option can be used with a variable created by pctile to fix a set of bins across multiple maps.
For example, when mapping a variable for numerous subpopulations (ex: wages by race) it can be desirable to hold the bins fixed in order to see an absolute comparison between the groups.
See Example 5 ("Comparisons between groups") for a click-through illustration.

cutvalues(numlist) specifies a list of values to be used as cutpoints for the color bins. The list must be ascending and contain no repeated values. This option cannot be combined with nquantiles() or cutpoints().

Colors

revcolor reverses the order of the colors.
By default, bins are colored in increasing intensity, from light yellow for the lowest values to dark red for the highest values. Specifying revcolor reverses this, assigning dark red to the lowest bins and light yellow to the highest bins.

propcolor spaces the colors used for each bin proportionally to the data, using the median values of each bin.

Consider a color spectrum located along [0,1]. Light yellow is located at 0 and dark red is located at 1.
The lowest bin always takes the light yellow located at 0, the highest bin always takes the dark red at 1.
By default, the middle bins are colored using elements of the color spectrum that are equally spaced between [0,1].
Specifying propcolor causes maptile to calculate the median value of each bin, and color the middle bins proportionally to the distances between them.
For example, if the bins are mostly clustered near the bottom and top of the range, then they will be mostly yellow and red, without much orange in the middle.

There is nothing objective about the distances on the color spectrum. The effect of propcolor is that bins whose data are relatively close together will look relatively similar in color.

shrinkcolorscale(#) shrinks the color spectrum to a fraction of its full size. # must be between 0 and 1.

Consider a color spectrum located along [0,1]. Light yellow is located at 0 and dark red is located at 1.
Specifying shrinkcolorscale(0.5) would cause maptile to color the bins using the spectrum from [0.25,0.75], reducing the variation in color.

This can be desirable when creating two maps of related variables where the range or variance of values plotted on one map is much smaller than on the other map.
Reducing the variation between the colors on one map visually indicates that the variation in the values being depicted is smaller.

There is nothing objective about the distances on the color spectrum.
The effect of shrinkcolorscale() is that the colors used become relatively more similar to one another.

rangecolor(colorstyle colorstyle) specifies the color spectrum boundaries. These are the colors of the lowest bin and the highest bin.
All bins between the lowest and the highest will take colors on the spectrum between these two boundaries.
By default, the boundary colors are yellow*0.1 and red*1.65.

fcolor(spmap_colorlist) specifies the color scheme, instead of using a color spectrum.
The color scheme can either be a colorstyle list or an spmap color scheme. This option cannot be combined with revcolor, propcolor, shrinkcolorscale() or rangecolor().

ndfcolor(colorstyle) specifies the color for areas with missing data.
The default is a light grey, gs12.

Legend

legdecimals(#) specifies the number of decimals to display in legend entries.
By default, the format of the numbers in the legend varies automatically with the magnitude of the data.
This option cannot be combined with legformat().

legformat(%fmt) specifies a numerical format for the numbers in the legend. By default, the format varies automatically with the magnitude of the data.
This option cannot be combined with legdecimals().

Output

savegraph(filename) saves the map to a file.
The format is automatically detected from the extension specified [ex: .gph .png .eps],
and either graph save or graph export is run.
If no file extension is specified .gph is assumed.

It is usually preferable to save maps in a bitmap format (.png or .tiff).
Many maps have an enormous file size when saved in a vector image format (.ps .eps .wmf .emf .pdf).
This happens because the map has very detailed information on the shapes of complicated borders and no details are lost when saving in a vector format.

replace specifies that the file being saved should overwrite any existing file.

resolution(#) scales the saved map image by the specified factor, which must be greater than 0. The default scaling factor is 1.

Advanced

mapif(condition) shows only the subset of areas selected by the if condition on the map.
It is important to understand how mapif() differs from an if or in statement.

An if or in statement selects what data is used. Observations excluded are treated as if the data is missing. They will therefore show up in grey on the map, and will not be included when computing quantiles.

mapif() selects what areas are shown, without affecting what data is used.
The quantiles are computed using all non-missing observations, whether or not they are shown on the map.
To additionally exclude the hidden areas from being used when calculating quantiles, it is necessary to repeat the condition using both if and mapif().

These differences are demonstrated in Example 4 ("Subsets of regions").

spopt(spmap_options) passes spmap options through to the spmap graph command.
In addition to the standard twoway options, spmap provides specialized options to customize the appearance of the generated map.
See Example 1 ("Binning") for a demonstration which alters the appearance of the legend.

Note that spmap supports twoway options, so enclosing twoway options in twopt() or spopt() are fully equivalent.

geofolder(folder_name) indicates the folder where the maptile geography template is located.
By default, maptile installs geographies to PERSONAL/maptile_geographies and loads them from that directory.
However, you may decide to keep the geography template files elsewhere on your computer.

hasdatabase specifies that the polygon ID variable (idvar) should not be merged onto the dataset, as it already exists in the dataset.
Manually merging the polygon ID variable onto the dataset can save a bit of processing time when creating numerous maps using the same geography.
But typically the gains are minimal.

Examples

Install a geography template for U.S. States.

. //files.michaelstepner.com/geo_state.zip""'

Load state-level 1980 U.S. Census data.

. sysuse census

Rename the geographic ID vars to match the variable names required by the state geography template.

. rename (state state2) (statename state)

Example 1: Binning

Plot the percentage of the population that are small children in each state.

. gen babyperc=poplt5/pop*100

. maptile babyperc, geo(state)

Small children are most common in the Western US.
But the bin of states with the highest percentage of children is much higher than the other 5 bins.

Try coloring each bin proportionally to its median value.

. maptile babyperc, geo(state) propcolor

. matrix list r(midpoints)

Most US states have a fairly similar proportion of children, but the highest group stands out.

Instead of grouping the states into quantile bins, now try coloring states individually and displaying a full spectrum in the legend.

. maptile babyperc, geo(state) spopt(legstyle(3)) cutvalues(5(0.5)13)

The proportion of children is very homogeneous across states, with Utah as a major exception.
Three other states also stand out a bit from the rest.

Example 2: Coloring

How do marriage rates vary across the US?

. gen marriagerate=marriage/pop*100

. maptile marriagerate, geo(state)

Quickly investigate that wide top bin (1.28-14.28).

. sum marriagerate, d

. list if marriagerate>2

. maptile marriagerate, geo(state) propcolor

Nevada is a huge outlier (because so many non-residents go to Las Vegas and get married).
But more broadly, the bins are quite evenly spaced.

Highlight the places with low marriage rates by reversing the colors, so that states with low marriage rates are dark red.

. maptile marriagerate, geo(state) revcolor

Let's make the colors a little splashier. Try the "Reds" color scheme built into spmap.

. maptile marriagerate, geo(state) nq(4) fcolor(Reds)

It could be splashier still. Let's manually definine a pink color spectrum.

. maptile marriagerate, geo(state) rangecolor(pink*0.1 pink*1.2)

Example 3: Formatting

Plot the percentage of the population living in an urban area

. gen urbanperc=popurban/pop*100

. maptile urbanperc, geo(state)

Let's add a legend title.

. maptile urbanperc, geo(state) legd(0) twopt(legend(title("Percent Urban" "Population")))

Alternatively, we can label the quantiles from Most Rural to Most Urban.

. maptile urbanperc, geo(state) twopt(legend(lab(2 "Most Rural") lab(3 "") lab(4 "") lab(5 "") lab(6 "") lab(7 "Most Urban")))

Note that numbering of legend entries starts at 2.

We can also give the map an explanantory title.

. maptile urbanperc, geo(state) legd(0) twopt(title("Percentage of State Population Living in Urban Areas"))

Example 4: Subsets of regions

This example illustrates the differences between using if and mapif() to select a subset of areas.

Start by creating a map of the median age in each state.

. maptile medage, geo(state)

Suppose we want to focus on the Northeast. Using an if statement controls what data are used.

. maptile medage if region==1, geo(state)

All the observations outside the Northeast were treated as if they were missing.
Only the Northeastern data was used to compute the quantiles.

Now let's zoom in on the Northeast. Using mapif() controls what data are shown.

. maptile medage, geo(state) mapif(region==1)

Only the Northeast is shown on the map.
But all observations were used to compute the quantiles.

To generate a map of only Northeastern data, we need to combine an if statement with mapif()

. maptile medage if region==1, geo(state) mapif(region==1)

This map shows the Northeast, categorized using the quantiles of the Northeastern states.

Example 5: Comparisons between groups

Load a dataset of US mortality rates by state and race.

. use http://files.michaelstepner.com/USmortality_by_state_race.dta

Look at how the mortality rates of white Americans and black Americans vary across states.

. maptile mort_white, geo(state) twopt(name(white))

. maptile mort_black, geo(state) twopt(name(black))

Comparing the two maps provides a relative comparison of the two groups.
The first map shows where white Americans have high mortality rates relative to other
white Americans. The second map shows how black Americans fare relative to other black Americans.
Looking at the two maps together, we can see that black Americans have relatively high mortality in the same states as white Americans.

But we might also be interested in an absolute comparison between the two groups.
How does the mortality of black Americans compare to that of white Americans?
To perform an absolute comparison, we need to hold the bins fixed.

Generate a variable containing the quantiles of the distribution of white mortality:

. pctile mortwhite_breaks=mort_white, nq(6)

Map both white and black mortality using the same bins:

. maptile mort_white, geo(state) twopt(name(whiteABS)) cutp(mortwhite_breaks)

. maptile mort_black, geo(state) twopt(name(blackABS)) cutp(mortwhite_breaks)

In nearly every state, black Americans have higher mortality rates than white Americans.

Saved Results

maptile saves the following in r():

Matrices

r(breaks) list of cut points between bins

r(midpoints) median value within each group (if propcolor specified)

Author

Michael Stepner

stepner@mit.edu

Acknowledgements

maptile was built on the shoulders of giants. Maps are generated using
spmap, written by Maurizio Pisati. The geography template shapefiles were made using
shp2dta, written by Kevin Crow, as well as mergepoly, written by Robert Picard.