help heatplothttp://github.com/benjann/heatplot/

Title

heatplot -- Command to create heat plots

Syntax

Syntax 1: Heat plot from variables

heatplot [z] y x [if] [in] [weight]
[,
z_options
yx_options
graph_options
generate_options
]

where z is a numeric variable (assumed constant if omitted), y
is a numeric variable or a string variable, and x is a numeric variable
or a string variable. Categorical y and x variables can be specified
as i.varname.

Syntax 2: Heat plot from Mata matrix

heatplot mata(name)
[,
z_options
yx_options
matrix_options
graph_options
generate_options
]

where name is a numeric Mata matrix (contents = z, row index = y,
column index = x).

Syntax 3: Heat plot from Stata matrix

heatplot matname [,
z_options
matrix_options
graph_options
generate_options
]

where matname is a Stata matrix
(contents = z, row names = y, column names = x).

z_options

levels(#) number of color bins

cuts(numlist) custom cut points for color bins

colors(palette) color map to be used for the color bins

backfill[(options)] fill background using first or last color

statistic(stat) (syntax 1 and 2 only) type of aggregation

fast (syntax 1 and 2 only) use fast aggregation; requires gtools

normalize normalize z values by the size of the covered area

transform(@exp) transform z values before creating color bins

size scale size of color fields by absolute values of z

size(spec) scale size of color fields by alternative values

sizeprop (syntax 1 only) scale size of color fields by relative frequencies

recenter (syntax 1 only) recenter color fields at data center within field

srange(lo [up]) set range of relative sizes of color fields

missing[(options)] display missing values

values[(options)] display numeric values as marker labels

hexagon[(options)] display color fields as hexagons
instead of rectangles; also see hexplot

scatter[(palette)] display marker symbols instead of color fields

keylabels(spec) determine how color fields are labelled in the legend

ramp[(options)] display a color ramp instead of the legend

p[#](area_options) detailed rendering of color fields

yx_options

[x|y]bins(spec) how
continuous y and x are binned

[x|y]bwidth(spec) how
continuous y and x are binned; alternative to bins()

[x|y]bcuts(numlist) how
continuous y and x are binned; alternative to bins()

[x|y]discrete[(#)] treat variables
as discrete and omit binning

[l|r|b|t]clip clip color fields at outer bounds

fillin(# [#]) (syntax 1 only) fill in empty combinations of (binned)
y and x by setting z to #

matrix_options

drop(numlist) drop elements equal to one of the values in numlist

lower only display lower triangle

upper only display upper triangle

nodiagonal omit diagonal

equations[(line_opts)] (syntax 3 only) label and outline equations

graph_options

nograph do not create a graph

[no]label do/do not use variable/value labels

addplot(plot) add other plots to the graph

addplotnopreserve technical option relevant for addplot()

by(varlist[, byopts]) (syntax 1 only) repeat plot by subgroups

twoway_options general twoway options

generate_options

generate[(namelist)] store
the plotted data as variables

replace allow overwriting existing variables

nopreserve replace the original data by
the plotted data

fweights, aweights, iweights, and pweights are allowed with Syntax 1; see help weight.

Description

heatplot creates heat plots from variables or matrices. One
example of a heat plot is a two-dimensional histogram in which the
frequencies of combinations of binned y and x are displayed as
rectangular (or hexagonal) fields using a color gradient. Another example
is a plot of a trivariate distribution where the color gradient is used to
visualize the (average) value of z within bins of y and
x. Yet another example is a plot that displays the contents of a matrix,
say, a correlation matrix or a spacial weights matrix, using a color
gradient. For a selection of different applications, see the
Examples below.

Dependencies

heatplot requires palettes (Jann 2018) and, in Stata 14.2 or newer,
colrspace (Jann 2019a). To install these packages, type

. ssc install palettes, replace
. ssc install colrspace, replace

The fast option requires gtools (Caceres Bravo 2018). To install
gtools, type

. ssc install gtools, replace
. gtools, upgrade

Options

z_options

levels(#) sets the number of color bins into which z (or the observed frequencies, if
z is omitted) is categorized, using a regular grid of intervals from the observed
minimum of (aggregated) z to the observed maximum. The intervals are right-open, except
for the last interval interval, which is right-closed. Only one of
levels() and cuts() is allowed.

cuts(numlist) specifies the thresholds used to categorize z,
where numlist is an ascending number list; see help
numlist. The intervals defined by the number list are right-open, except
for the last interval, which is right-closed. If the smallest number is
larger than the observed minimum of (aggregated) z, an extra interval
will be added at the bottom. Likewise, if the largest number is smaller than the
maximum, an extra interval will be added at the top. Within the number list,
you can use @min and @max to denote the
observed minimum and maximum, respectively. For example, you could type

@min(20)@max

to create intervals from the minimum to the maximum in steps of 20. Furthermore,
expressions specified as {exp} will be evaluated
before expanding the number list. For example, you could type

{@min-.5}(1){@max+.5}

to create intervals from the observed minimum minus 0.5 to the observed maximum
plus 0.5 in steps of 1.

colors([palette] [,
palette_options])
selects the color palette to be used for the bins of z. This also
sets the number of bins, unless levels() or cuts() is specified. palette is any
palette allowed by colorpalette (which can also be a simple list of colors, see
help colorlist) and palette_options are
corresponding options. The default is colors(viridis). For example, to use a
red to blue HCL color scheme, you could type colors(hcl bluered, reverse). In
Stata versions older than 14.2, heatplot uses command
colorpalette9 instead of colorpalette
and sets the default to colors(hcl, viridis).

backfill[(options)] fills the background (the plotregion)
using the first color of the colors provided by colors(). This makes
sense, for example, in a bivariate histogram. When applying backfill,
you may want to turn grid lines off; in most situations this can be achieved by
typing ylabel(, nogrid) and/or xlabel(, nogrid). options are:

last uses the last color instead of the first color.

inner only colors the inner plotregion. The default is to color both,
the inner and the outer plotregion.

statistic(stat) sets the type of aggregation of z values within
yx-bins. statistic() is only allowed in syntax 1 and 2 (in syntax 3,
each cell of the specified matrix constitutes a separate color field; hence, there is
no aggregation). stat can be any statistic supported by collapse. In
addition, stat can be proportion to compute proportions (rather
than percentages) or asis to skip aggregation. The main purpose of
asis is to save computer time in cases where no aggregation is
needed; typically, you only want to specify asis if you are certain
that all combinations of (binned) y and x are unique.

In syntax 1, if variable z is provided, the default is
statistic(mean); if z is omitted, the default is
statistic(percent). In syntax 2, the default is statistic(sum),
or, if discrete has been specified, statistic(asis).

fast performs some of the computations using fast commands provided
by gtools (e.g. gcollapse instead of official collapse
for aggregation). Use this option to speed up computations in very large
datasets. The gtools package (Caceres Bravo 2018) has to be
installed on the system; see http://github.com/mcaceresb/stata-gtools
for more information. Option fast is only allowed in syntax 1 and 2.

normalize causes the (aggregated) z values to be normalized by the size
of the area covered by a color field before assigning colors. For example, specifying
normalize together with statistic(proportion) will visualize densities
instead of proportions. normalize may be useful if you clip the color
fields using option clip or if you apply option
bcuts() in a way such that color fields have different
sizes. The area covered by a color field will be computed before rescaling
the fields according to size() or
sizeprop. If option
scatter is specified, the sizes of the areas
will be computed as if scatter was not specified. If
option hexagon is specified, the computations will
be based on the (possibly clipped) shapes of the hexagons. normalize
has no effect in syntax 3.

transform(@exp) causes the (aggregated and, possibly, normalized) z
values to be transformed before assigning colors. @exp is
an expression (see exp) in which @ acts as a placeholder
for the values to be transformed. For example, to take the natural logarithm,
type transform(ln(@)).

size[(spec)] scales the sizes of the color fields. If
size is specified without argument, the color fields will be scaled in
proportion to the absolute value of (aggregated and, possibly,
normalized) z. Alternatively, provide a custom source for the scaling as
follows.

In syntax 1, specify
size(exp[, statistic(stat)])
to obtain the size information from exp (typically, exp
is a simple variable name). Observations for which exp is missing will
not be excluded from the estimation sample; if exp is missing for
all observations within a specific color field, the size of the field will
be set to the minimum as set by srange().

In syntax 2, specify
size(name[, statistic(stat)])
to obtain the size information from Mata matrix name. The matrix must
be numeric and have the same dimension as the main matrix.

In syntax 3, specify size(matname) to obtain the size information
from Stata matrix matname. The matrix must have the same dimension
as the main matrix.

In syntax 1 and 2, suboption statistic(stat) sets the type
of aggregation, where stat can be any statistic supported by
collapse (the default is mean). Suboption statistic()
is only relevant if the main statistic() option
has not been set to asis. In any case, absolute values of the
(possibly aggregated) information will be used for the scaling.

sizeprop scales the size of the color fields in proportion to the
relative frequency of the underlying data. Use sizeprop as an
alternative to size(). sizeprop is only allowed in syntax 1.

recenter moves the color fields such that their center is at
the center of the included data (mean of y and x within the bin). This can
be useful if size() or sizeprop has been specified. recenter is only allowed
in syntax 1.

srange(lo [up]) sets the range of relative sizes of
the color fields. srange() is only relevant if size() or
sizeprop has been specified. Let v, v>=0, be the variable to which the
field sizes should be proportional (e.g. relative frequencies). The field
sizes are then computed as lo + v/max(v) *
(up - lo). The default is lo=0 and up=1, that is, the smallest
possible field has size 0 (invisible) and the largest field has size 1
(full size). Specify, for example, srange(0.5) to set the size of the
smallest possible field to 0.5 (half of full size).

missing[(options)] displays color fields for
combinations of (binned) y and x for which (aggregated)
z is equal to missing. options are:

label(label) sets the text to be used for missing values in the legend. The
default is label("missing").

area_options are options to affect the look of the missing
value color fields; see help area_options. The default is to
display the fields in black.

values[(options)] displays the z values (or other information)
as marker labels in the middle of the color fields. options are:

label(spec) determines the source of the values of the labels. The
default is to display the (aggregated and, possibly, normalized) z
values. Alternatively, provide a custom source as follows.

In syntax 1, specify
label(exp[, statistic(stat)])
to display the (aggregated) value of exp (typically, exp
is a simple variable name). Observations for which exp is missing will
not be excluded from the estimation sample. The default for
stat is mean if exp is numeric and first if exp is string.

In syntax 2, specify
label(name[, statistic(stat)])
to obtain the values from Mata matrix name. The matrix must
be numeric and have the same dimension as the main matrix. The default for
stat is mean.

In syntax 3, specify label(matname) to obtain the values
from Stata matrix matname. The matrix must have the same dimension
as the main matrix.

In syntax 1 and 2, suboption statistic(stat) sets the type of
aggregation, where stat can be any statistic supported by
collapse. The suboption is only relevant if the main
statistic() option has not been set to asis.

transform(@exp) causes the values to be transformed before
displaying. @exp is an expression (see exp) in which
@ acts as a placeholder for the values to be transformed. The result
of @exp may be numeric or string; for example, you could type
transform(cond(@>0, "+", cond(@<0, "-", ""))) to display "+" or "-"
(or nothing) depending on whether the value is (strictly) positive or
(strictly) negative.

style(markerlabelstyle) sets the overall style of the labels.

position(clockposstyle) specifies where the label is to be located
relative to the middle of the color field. The default is position(0)
(centered).

gap(size) specifies how much space should be put between the
label the middle of the color field. This is only relevant if position()
is not 0.

angle(anglestyle) specifies the angle of the text.

size(textsizestyle) specifies the size of the text.

color(colorstyle) specifies the color of the text. Default is
color(black) (unless style() is specified in which case the
color is determined by the selected style).

format(%fmt) sets the display format for the values. This option is
only useful if the labels are numeric.

For more details on options style() through format() also see
the corresponding options with "mlab" prefix in marker_label_options.

hexagon[(options)] causes the color fields to be rendered as
hexagons instead of rectangles; also see hexplot. hexagon and
scatter are not both allowed. options are:

horizontal arranges the hexagons horizontally. The default is to arrange
the hexagons vertically.

left starts with a left-shifted hexagon row. The default is to start
with a right-shifted row. If horizontal is specified, left
starts with an down-shifted row instead of an up-shifted row.

odd uses an odd number of hexagon columns. The default is to use
an even number of columns. That is, by default the bins on the x-axis are
constructed in a way such that each bin contains a double column of hexagons,
yielding an even overall number of columns. Specify odd to construct the
bins in a way such that the last bin only contains a single column. If
horizontal is specified, odd affects the number of
rows rather than columns.

scatter[(palette [,
palette_options])] causes the heat
plot to be rendered as a scatter plot, with markers placed at the centers
of the bins. Only one of scatter and hexagon is allowed. palette
is any palette allowed by symbolpalette (which can also be a simple list of
symbol styles, see help symbollist) and
palette_options are corresponding options. The default is
scatter(circle). If less symbol styles are specified than there are
bins of z, the symbols will be recycled.

keylabels(spec) selects the legend keys to be labeled and affects the
formatting of the labels. spec
is

[rule] [, suboptions ]

where rule may be

numlist label the specified keys, where 1 refers to the first key (lowest value), 2 to the second, etc.

minmax label the lower boundary of the first key and the upper boundary of the last key

none omit the labels

all label all keys; this is the default unless there are more than 24 keys

and suboptions are:

format(%fmt) sets the display format. The default is %7.0g.

transform(@exp) causes the values to be transformed before being
displayed. @exp is an expression in which @ acts as
a placeholder for the values to be transformed. Typically, @exp will be
the inverse of the main transform()
option. Example: transform(ln(@)) would go along with
keylab(,transform(exp(@)).

interval uses interval notation for the key labels, e.g. [0,10),
[10,20), etc. Only one of interval and range()
is allowed. The default is to display interval midpoints. interval
has no effect if rule is minmax.

range(#) uses range notation for the key labels. Argument # specifies by how much the upper
bound should be reduced. For example, range(1) would display interval [10,20) as "10-19", whereas
range(0.1) would display the interval as "10-19.9". You may want to set an appropriate
display format when specifying range(); see format() above. interval and range()
are not both allowed. range() has no effect if rule is minmax.

area displays legend keys as areas (rectangles) even if scatter has been specified.

textbox_options are general options to affect the rendering of the
labels, such as size(); see textbox_options.

legend_options are further options affecting the rendering of the
legend; see contents and location in help legend_options.

ramp[(options)] renders the legend as a color ramp
instead of using graph's legend
option. Internally, if ramp is specified, two graphs are created, one
for the main plot and one for the color ramp; these plots are then combined into a single graph
using graph combine. options are:

left, right, top, or bottom specify the location
of the ramp on the final graph. The location also affects the orientation of
the ramp. In case of top or bottom, the ramp
will be oriented horizontally; in case of left or right, the ramp
will be oriented vertically. The default is bottom.

labels(rule_or_values) specifies how the axis of the ramp
should be labeled and ticked, where rule_or_values is as described in
axis_label_options. You may specify @min
and @max to refer to the lower bound of the first interval and the
upper bound of the last interval. For example, you could type
labels(@min .5 @max) to place a label at the minimum, at 0.5, and at the maximum. Various
suboptions are available to control the rendering of the labels and ticks; see
axis_label_options.

format(%fmt) sets the display format for the labels. The default
is %7.0g.

length(#) sets the length of the ramp as a percentage of the
available space (the graph's width or height, depending on the orientation
of the ramp). In horizontal orientation the default is length(80); in
vertical orientation the default is length(60).

space(#) specifies the space to be consumed by the plot containing
the ramp, as a percentage of the overall size of the graph. In horizontal
orientation the default is space(12); in
vertical orientation the default is space(20).

transform(@exp) causes the ramp to be displayed on a transformed
scale. @exp is an expression in which @ acts as
a placeholder for the values to be transformed. Typically, @exp will be
the inverse of the main transform()
option. For example, transform(ln(@)) would go along with
ramp(transform(exp(@)).

combine(combine_options) are options to be passed through to
graph combine, such as region_options. Note that the
following options will be collected from the main options
and passed through to graph combine automatically: title(),
subtitle(), note(), caption(), ysize(),
xsize(), nodraw, scheme(), name(), and
saving().

twoway_options are general options to be applied to the plot
containing the color ramp.

p[#](area_options) provides options to affect the rendering of
the color fields; see help area_options. For example, if you want
the fields to have black outlines, you can type p(lcolor(black) lalign(center)). Unnumbered
option p() affects all color fields. In addition, to address only the fields
corresponding a specific level of z, you can type p#()
where # is the number of the level. For example, if you want the color fields
of the 3rd level to have red outlines, you could type
p3(lcolor(red)).

yx_options

bins(spec) or bwidth(spec), ybins(spec) or ybwidth(spec),
and xbins(spec) or xbwidth(spec) specify how
y and x are binned. These options are only allowed with
continuous variables. bins()/bwidth() affects both,
y and x. ybins()/ybwidth() and
xbins()/xbwidth() only affect y or x, respectively, taking precedence over
bins()/bwidth(). spec is

[n lb ub] [, suboptions ]

for bins() and

[width lb ub] [, suboptions ]

for bwidth() where

n number of bins

width bin width

lb midpoint (or lower bound) of first bin

ub midpoint (or upper bound) of last bin

If neither n nor width is specified, the
default is to set n to trunc(min(sqrt(N), 10*ln(N)/ln(10))^(9/10))
(or a fraction thereof if lb and ub define a range that is
smaller than the observed data range), where N is the number of
observations. If lb and ub are
omitted, they are set to the observed minimum and maximum of the data,
respectively. Default values can also be requested
by typing "." instead of providing a number. For example, you could type
bins(. 0 10) to create bins from 0 to 10 using the default number
of bins. Data outside the bin range
defined by lb and ub will not be displayed, but will be taken into
account when computing relative frequencies. suboptions are:

tight makes the bins tight. By default lb and ub are
interpreted as midpoints of the the first and last bins. Specify
tight to treat lb and ub as outer bounds of the the first
and last bins (in general, all bins are defined using right-open intervals;
however, if tight is specified, observations equal to ub will
be included in the last bin). If tight is specified together with hexagon,
the first and last bins are made as tight as possible given the shape and
arrangement of the hexagons; all data falling into the hexagons will be
taken into account even if lower than lb or larger than ub
(unless option clip is specified).

ltight makes the first bin tight, but leaves the last bin unchanged.

rtight makes the last bin tight, but leaves the first bin unchanged.

Note on setting the number of bins or the bin width for hexagon
plots: In a grid of true hexagons, the vertical distance between hexagons
midpoints is smaller than the horizontal distance by a factor of
sqrt(3)/2 (or vice versa if hexagon(horizontal) is specified). If applying graph's
aspectratio(1) option to produce a square plot, you may thus want to
set the number of y-bins to about 2/sqrt(3) times the number x-bins. Likewise, if
y and x have the same scale, you may want to set the width of y-bins to
sqrt(3)/2 times the width of x-bins.

bcuts(numlist), ybcuts(numlist) and xbcuts(numlist)
specify how y and x are binned. Use these options as an alternative
to [y|x]bins() or [y|x]bwidth(). bcuts()
affects both, y and x; ybcuts() and xbcuts() only affect y or x,
respectively, taking precedence over bcuts(). numlist is an (ascending)
list of (at least two) cutpoints defining the bins. The bins are defined
as right-open intervals from one cutpoint to the next (except for the last bin
which is right-closed). Data smaller than the first cutpoint or larger then
the last cutpoint will not be displayed, but will be taken into
account when computing relative frequencies. Option clip
will have no effect for variables binned by bcuts(). Option
hexagon is not allowed with bcuts().

discrete[(#)], ydiscrete[(#)], and xdiscrete[(#)]
specify that the variables are discrete and should not be binned. discrete
affects both, y and x. ydiscrete and xdiscrete only affect y or x,
respectively. Typically, treating variables as discrete only makes sense if
their values are regularly spaced, as heatplot will print color fields
centered at each observed value (furthermore, although allowed, specifying
hexagon together with discrete does not
lead to useful results in most situations). Optional argument #
specifies the step width affecting the size of the color fields. The default
step width is 1. Categorical variables specified as i.varname are always treated as
discrete, but you can still use [y|x]discrete(#) to affect the size of the color fields
in this case.

clip, rclip, lclip, tclip, and bclip
cause the color fields to be clipped at the lower and upper bounds of the
data range (or the range selected by lb and ub in bins() or bwidth(); data
outside the clipped range will be omitted in this case). clip
causes clipping on all four sides, rclip clips on the right,
lclip clips on the left, tclip clips at the top, and bclip
clips at the bottom (any combination is allowed). Option normalize
will only take into account the remaining area of a field after clipping.

fillin(value [size]) fills in empty combinations of (binned) y and x
by setting z to value. value can be . to set z to missing,
which will be displayed if the missing option has been specified. Optional size
is a number between 0 and 1 that sets the relative size of the color fields created by
fillin(); this is only relevant if size() or sizeprop
has been specified. size defaults to 1. fillin() is only allowed in
syntax 1. See backfill for a more efficient (but less
flexible) approach to color empty combinations of y and x.

matrix_options

drop(numlist) drops cells that have a value equal to one of the
specified numbers. For example, type drop(0) to omit cells that contain 0.

lower causes only the lower triangle of the matrix to be displayed. Only one of lower and
upper is allowed.

upper causes only the upper triangle of the matrix to be displayed. Only one of upper and
lower is allowed.

nodiagonal omits the diagonal of the matrix.

equations[(line_options)] uses the equation
names of the matrix as axis labels, places ticks between equations, and
draws outlines around diagonal equation areas. This
can be useful, for example, if the matrix contains pairwise distances and the
equations identify clusters. Use line_options to affect the
rendering of the outline. equations() is only allowed in
syntax 3.

graph_options

nograph omits creating a graph.

[no]label specifies whether variable and value labels should be used or not. In syntax 1
(plot from variables) the default is to use the variable labels of y and x
as axis titles and, for categorical variables, the value labels as tick
labels, if variable and value labels exist. Specify nolabel to
use variable names and values instead. In syntax 3 (plot from Stata matrix) the default is to use
row and column names as tick labels. Specify label to instruct heatplot to
look for corresponding variables in the dataset and use their labels. In syntax 2, label
has no effect.

addplot(plot) provides a way to add other plots to the generated graph; see help addplot_option.

addplotnopreserve drops the original data when drawing the graph even if
addplot() has been specified. By default, heatplot temporarily deletes the
original data to speed up drawing the graph. However, if addplot() is
specified, the original data is preserved because addplot() might
make use of it. If you are certain that addplot() does not make use of the original data
(for example, because it only contains a scatteri plot), you can
specify addplotnopreserve to save memory and computing time in large datasets.

by(varlist [, byopts]) specifies that the plot should be repeated for each set of values of varlist; see help
by_option (but note that suboption total is not supported). by() is only allowed in syntax 1. Computation
of relative frequencies will be across all by-groups.

twoway_options are any other options documented in help twoway_options.

generate_options

generate[(namelist)] stores the plotted data as new
variables. Depending on context, generate() might need to increase the
number of rows in the dataset to store the variables (by default, five rows
are required per color field, the coordinates of the four corners plus
missing as delimiter; if option scatter is specified,
only one row per field is required; if option hexagon
is specified, 7 or 9 rows are required depending on whether
clip has been specified). The default
variable names are:

_Z (aggregated) values of z
_Zid categorized z
_Y y midpoints
_Yshape y shape coordinates
_X x midpoints
_Xshape x shape coordinates
_Size field size (if relevant)
_Mlab marker label (if relevant)

Alternatively, specify namelist containing a custom list of
variable names. If the list contains fewer elements than the number of
variables to be generated, the above names are used for the remaining variables.

If you only want to generate the variables without drawing a graph,
apply the nograph option.

replace allows overwriting existing variables.

nopreserve instructs generate() to replace the original data by
the new variables. The default is to keep the original data.

Examples

Also see Jann (2019b).

Histograms

Bivariate histogram of weight and height:

. webuse nhanes2, clear
. heatplot weight height, ylabel(25(25)175)

Using first color for background:

. heatplot weight height, ylabel(25(25)175, nogrid) backfill colors(magma, reverse)

Using hexagons instead of rectangles:

. heatplot weight height, ylabel(25(25)175, nogrid) backfill colors(magma, reverse) hexagon

Make size of hexagons proportional to the relative frequency and shift
their midpoints to the empirical centers of the included data:

. heatplot weight height, ylabel(25(25)175, nogrid) backfill colors(magma, reverse) hexagon sizeprop recenter

Report counts instead of percentages and change labels in legend:

. heatplot weight height, ylabel(25(25)175, nogrid) backfill colors(magma, reverse) hexagon sizeprop recenter statistic(count) cuts(1(5)96 100) keylabels(, range(1))

Display color ramp instead of legend

By default, a legend produced by graph's legend option is
displayed. Alternatively, use the ramp option to render the legend as
a color ramp in a separate coordinate system (internally,
graph combine will be employed to combine the main plot and the
ramp in a single graph):

. webuse nhanes2, clear
. heatplot weight height, ramp

Place ramp on right, adjust the space used for the
ramp, specify custom labels:

. heatplot weight height, ramp(right space(12) label(0(.1).9))

Use text labels and remove title:

. heatplot weight height, ramp(right label(@min "low" @max "high") subtitle(""))

Assign colors based on a transformed scale and retransform the ramp:

. heatplot weight height, stat(count) transform(ln(@)) ramp(transform(exp(@)))

Trivariate distributions

The following graph displays the gender distribution (proportion female) by weight and height:

. webuse nhanes2, clear

. heatplot female weight height, hexagon ylabel(25(25)175) cuts(0(.05)1)

The same graph additionally taking into account relative frequencies:

. heatplot female weight height, hexagon ylabel(25(25)175) cuts(0(.05)1) sizeprop recenter

Distribution of the body mass index by gender and its relation to high blood pressure:

. heatplot highbp bmi i.female, xdiscrete(0.9) yline(18.5 25) cuts(0(.05).75) sizeprop recenter colors(inferno) plotregion(color(gs11)) ylabel(, nogrid)

Sea surface temperature by longitude, latitude, and date:

. sysuse surface, clear

. heatplot temperature longitude latitude, bwidth(.5) statistic(asis) by(date, legend(off)) ylabel(30(1)38) aspectratio(1)

In this data, longitude and latitude are on a regular grid with a step width of half a degree. This is why
we set the bin width to 0.5 using option bwidth(.5). Furthermore, for each
combination of date, longitude, and latitude there is only a single temperature measurement. This
is why we can add option statistic(asis). The option is not strictly needed, it just skips unnecessary
computations.

Same plot using hexagons:

. heatplot temperature longitude latitude, hexagon bwidth(.5) clip statistic(asis) by(date, legend(off)) ylabel(30(1)38) aspectratio(1)

Option clip has been specified to clip the hexagons at the outer bounds of the data.

Correlation matrix

Correlation matrix including correlation coefficients as marker labels:

. sysuse auto, clear

. correlate price mpg trunk weight length turn foreign

. matrix C = r(C)

. heatplot C, values(format(%9.3f)) color(hcl diverging, intensity(.6)) legend(off) aspectratio(1)

Display only lower triangle and omit the diagonal:

. heatplot C, values(format(%9.3f)) color(hcl diverging, intensity(.6)) legend(off) aspectratio(1) lower nodiagonal

An issue with correlation graph above is that the color gradient is not
centered at zero. If using a diverging gradient, we would probably want the
center of the gradient to denote a correlation of zero, and then
use symmetric intervals on both sides. Use the cuts()
option control how the intervals are constructed. Examples:

. heatplot C, color(hcl diverging, intensity(.6)) aspectratio(1) cuts(-1.05(.1)1.05)

. heatplot C, color(hcl diverging, intensity(.6)) aspectratio(1) cuts(-1(`=2/15')1) keylabels(, interval)

As seen above, option values() can be used to display the values of the correlations
with the color fields. It is also possible to print alternative information collected from
a second matrix using suboption label(). In the following example, p-values are printed:

. pwcorr price mpg trunk weight length turn foreign, sig

. matrix C = r(C)

. matrix sig = r(sig)

. heatplot C, values(label(sig) format(%9.3f)) color(hcl diverging, intensity(.6)) legend(off) aspectratio(1)

Furthermore, suboption transform() can be used to edit the labels. Here is an
example that marks non-significant correlations:

. heatplot C, values(label(sig) transform(cond(@>.05, "n.s.", ""))) color(hcl diverging, intensity(.6)) legend(off) aspectratio(1)

Dissimilarity matrix with clusters

Illustration of the use of the equations() option:

. sysuse lifeexp, clear
. keep if gnppc<.
. cluster wards popgrowth lexp gnppc
. cluster generate N = groups(`=_N'), ties(fewer)
. cluster generate G = groups(5)
. sort G N
. matrix dissim D = popgrowth lexp gnppc
. `"mata: st_matrixcolstripe("D", strofreal(st_data(., "G N")))"'
. `"mata: st_matrixrowstripe("D", strofreal(st_data(., "G N")))"'

. heatplot D, equations(lcolor(red)) plotregion(margin(zero)) legend(off) aspectratio(1) xscale(alt)

Spacial weights matrix

Setup:

. copy http://www.stata-press.com/data/r15/homicide1990.dta .
. copy http://www.stata-press.com/data/r15/homicide1990_shp.dta .
. use homicide1990
. spmatrix create contiguity W (this may take a while)
. spmatrix matafromsp W id = W

Heat plot with default settings, ignoring cells (i.e. weights) that are
equal to zero:

. heatplot mata(W), drop(0) aspectratio(1)

Hexagon plot with fine-grained resolution:

. heatplot mata(W), drop(0) aspectratio(1) hexagon bins(100)

Plotting each cell individually using the discrete option:

. heatplot mata(W), drop(0) aspectratio(1) discrete color(black) p(lalign(center))

Since in this matrix all (non-zero) weights have the same value, we only need a single
color, requested by color(black). Furthermore, p(lalign(center)) has been specified
to prevent the individual color fields from becoming (almost) invisible.

A very similar plot can also be produced using the scatter option:

. heatplot mata(W), drop(0) aspectratio(1) discrete color(black) scatter p(ms(p))

Returned results

Scalars

r(N) number of observations

r(levels) number of z levels (colors)

r(y_k) number of y bins

r(y_wd) y bin width

r(y_lb) midpoint (or lower bound) of first y bin

r(y_ub) midpoint (or upper bound) of last y bin

r(x_k) number of x bins

r(x_wd) x bin width

r(x_lb) midpoint (or lower bound) of first x bin

r(x_ub) midpoint (or upper bound) of last x bin

Macros

r(ztitle) legend title

r(ytitle) y-axis title

r(xtitle) x-axis title

r(colors) list of color codes

r(keylabels) legend keys

r(eqcoords) coordinates of equation outlines

Matrices

r(cuts) cut points used to categorize z

References

Caceres Bravo, M. (2018). GTOOLS: Stata module to provide a fast
implementation of common group commands. Available from
http://ideas.repec.org/c/boc/bocode/s458514.html (also see
http://github.com/mcaceresb/stata-gtools).

Jann, B. (2018). Color palettes for Stata graphics. The Stata Journal
18(4): 765-785.

Jann, B. (2019a). ColrSpace: Mata class for color management. Available from
http://ideas.repec.org/c/boc/bocode/s458597.html.

Jann, B. (2019b). Heat (and hexagon) plots in Stata. Presentation at London
Stata Conference 2019. Available from http://ideas.repec.org/p/boc/usug19/24.html.

Author

Ben Jann, University of Bern, ben.jann@unibe.ch

Thanks for citing this software as follows:

Jann, B. (2019). heatplot: Stata module to create heat plots and hexagon plots. Available from
http://ideas.repec.org/c/boc/bocode/s458598.html.

Also see

Online: help for hexplot, colorpalette,
twoway contour