This document shows how measurement units in R, provided by the units package, are used automatically in axis labels of plots.
First, we make sure a superscript in the y-axis label doesn’t run off the left edge:
mar = par("mar") + c(0, .5, 0, 0)
par(mar = mar)
In this document we need to pass mar
to every plot
command, because each R section resets the plotting parameters; in a normal R script you need to call par
only once at the start.
Convert mdcars
variables to SI units:
library(units)
displacement = mtcars$disp * ud_units[["in"]]^3
(in
is treated specially, because it is also a reserved word in R)
units(displacement) = with(ud_units, cm^3)
weight = mtcars$wt * 1000 * with(ud_units, lb)
units(weight) = with(ud_units, kg)
par(mar = mar)
plot(weight, displacement)
Change grouping symbols from [ ]
into ( )
:
units_options(group = c("(", ")") ) # parenthesis instead of square brackets
par(mar = mar)
plot(weight, displacement)
Remove grouping symbols, increase space between variable name and unit:
units_options(sep = c("~~~", "~"), group = c("", "")) # no brackets; extra space
par(mar = mar)
plot(weight, displacement)
Increase space between variables inside units, plot without negative power, with division bar:
units_options(sep = c("~", "~~"), group = c("[", "]"))
gallon = make_unit("gallon")
consumption = mtcars$mpg * with(ud_units, mi/gallon)
units(consumption) = with(ud_units, km/l)
par(mar = mar)
plot(displacement, consumption) # division in consumption
Plot with negative powers:
units_options(negative_power = TRUE) # division becomes ^-1
par(mar = mar)
plot(displacement, consumption)
Plot expressions, modifying units on the fly:
par(mar = mar)
plot(1/displacement, 1/consumption)