Graphics with the mosaic package

Randall Pruim

August, 2014

This vignette is simply a suite of plots that exist primarily as part of our quality control for the package. But since the examples might be useful to others as well, we’ve added this as a vignette in the package.

lattice extras

The mosaic package resets the default panel function for histograms. This changes the default for bin selection and provides some additional arguments to histogram.

histogram(~ rbinom( 500, 20, .3), width=1, fit="normal", v=c(6,10), h=0.1 )

ladd()

ladd() provides a relatively easy way to add additional things to a lattice graphic.

xyplot( rnorm(100) ~ rnorm(100) )
ladd( grid.text("Here is some text", x=0, y=0, default.units="native") )
ladd( panel.abline( a=0, b=1, col="red", lwd=3, alpha=.4 ) )
ladd( panel.rect(x=-1, y=-1, width=1, height=1, col="gray80", fill="lightsalmon"))
ladd( panel.rect(x=0, y=0, width=2, height=2, col="gray80", fill="lightskyblue"), 
      under=TRUE)

mplot()

In addition to the interactive uses of mplot(), it can be used in place of plot() in several settings.

require(gridExtra)
## Loading required package: gridExtra
mod <- lm( width ~ length * sex, data=KidsFeet )
mplot(mod, which=1:7, multiplot = TRUE, ncol=2)
## TableGrob (4 x 2) "arrange": 8 grobs
##   z     cells    name
## 1 1 (1-1,1-1) arrange
## 2 2 (1-1,2-2) arrange
## 3 3 (2-2,1-1) arrange
## 4 4 (2-2,2-2) arrange
## 5 5 (3-3,1-1) arrange
## 6 6 (3-3,2-2) arrange
## 7 7 (4-4,1-1) arrange
## 8 8 (4-4,2-2) arrange
##                                                             grob
## 1                                       lattice[GRID.lattice.39]
## 2                                       lattice[GRID.lattice.40]
## 3                                       lattice[GRID.lattice.41]
## 4                                       lattice[GRID.lattice.42]
## 5                                       lattice[GRID.lattice.43]
## 6                                       lattice[GRID.lattice.44]
## 7                                       lattice[GRID.lattice.45]
## 8 model:  lm(formula = width ~ length * sex, data = KidsFeet) \n
mplot(mod, which=1:7, system="ggplot", ncol=2)
## geom_smooth: method="auto" and size of largest group is <1000, so using loess. Use 'method = x' to change the smoothing method.
## geom_smooth: method="auto" and size of largest group is <1000, so using loess. Use 'method = x' to change the smoothing method.
## geom_smooth: method="auto" and size of largest group is <1000, so using loess. Use 'method = x' to change the smoothing method.
## geom_smooth: method="auto" and size of largest group is <1000, so using loess. Use 'method = x' to change the smoothing method.
## TableGrob (4 x 2) "arrange": 8 grobs
##   z     cells    name
## 1 1 (1-1,1-1) arrange
## 2 2 (1-1,2-2) arrange
## 3 3 (2-2,1-1) arrange
## 4 4 (2-2,2-2) arrange
## 5 5 (3-3,1-1) arrange
## 6 6 (3-3,2-2) arrange
## 7 7 (4-4,1-1) arrange
## 8 8 (4-4,2-2) arrange
##                                                             grob
## 1                                                 gtable[layout]
## 2                                                 gtable[layout]
## 3                                                 gtable[layout]
## 4                                                 gtable[layout]
## 5                                                 gtable[layout]
## 6                                                 gtable[layout]
## 7                                                 gtable[layout]
## 8 model:  lm(formula = width ~ length * sex, data = KidsFeet) \n
mplot(mod, which=7)
## TableGrob (2 x 1) "arrange": 2 grobs
##      z     cells    name
##      1 (1-1,1-1) arrange
## main 2 (2-2,1-1) arrange
##                                                                grob
##                                           lattice[GRID.lattice.348]
## main model:  lm(formula = width ~ length * sex, data = KidsFeet) \n
mplot(mod, which=7, rows=-1)
## TableGrob (2 x 1) "arrange": 2 grobs
##      z     cells    name
##      1 (1-1,1-1) arrange
## main 2 (2-2,1-1) arrange
##                                                                grob
##                                           lattice[GRID.lattice.349]
## main model:  lm(formula = width ~ length * sex, data = KidsFeet) \n
mplot(mod, which=7, rows=c("sexG", "length", "length:sexG"), 
      title="Custom titles are supported")
## TableGrob (2 x 1) "arrange": 2 grobs
##      z     cells    name                        grob
##      1 (1-1,1-1) arrange   lattice[GRID.lattice.350]
## main 2 (2-2,1-1) arrange Custom titles are supported
mod <- lm(age ~ substance, data=HELPrct)
mplot(TukeyHSD(mod))

mplot(TukeyHSD(mod), system="ggplot")

plotFun() and makeFun()

mod <- lm(width ~ length* sex, data = KidsFeet)
L <- makeFun(mod)
L( length=15, sex="B")
##        1 
## 7.041437
L( length=15, sex="G")
##        1 
## 6.654868
xyplot(width ~ length, groups = sex, data = KidsFeet, auto.key=TRUE)
plotFun( L(length, sex="B") ~ length, add=TRUE, col=1 )
## converting numerical color value into a color using lattice settings
plotFun( L(length, sex="G") ~ length, add=TRUE, col=2 )
## converting numerical color value into a color using lattice settings
## converting numerical color value into a color using lattice settings

For logistic regression, makeFun() handles the conversion back to probabilities by default.

mod <- glm( SmokeNow =="Yes" ~ Age + Race3, data=NHANES, family=binomial())
SmokerProb <- makeFun(mod)
xyplot( SmokeNow=="Yes" ~ Age, groups=Race3, data=NHANES, alpha=.01, xlim=c(20,90) )
plotFun(SmokerProb(Age, Race3="Black") ~ Age, col="black", add=TRUE)
plotFun(SmokerProb(Age, Race3="White") ~ Age, col="red", add=TRUE) 
ladd(grid.text("Black", x=25, y=SmokerProb(25, Race="Black"),hjust = 0, vjust=-0.2,
               gp=gpar(col="black"),
               default.units="native"))
ladd(grid.text("White", x=25, y=SmokerProb(25, Race="White"),hjust = 0, vjust=-0.2,
               gp=gpar(col="red"),
               default.units="native"))

f <- makeFun(sin(x) ~ x)
plotFun( f(x) ~ x, xlim = c( -2 * pi, 2 * pi) )

plotFun( x * sin(1/x) ~ x, xlim=c(-1,1) )

plotFun( x * sin(1/x) ~ x, xlim=c(-1,1), npts=10000 )

Visualizing distributions

plotDist("chisq", df=3)

plotDist("chisq", df=3, kind="cdf")

xpnorm(80, mean=100, sd=15)
## 
## If X ~ N(100,15), then 
## 
##  P(X <= 80) = P(Z <= -1.333) = 0.0912
##  P(X >  80) = P(Z >  -1.333) = 0.9088

## [1] 0.09121122
xpnorm(c(80,120), mean=100, sd=15)
## 
## If X ~ N(100,15), then 
## 
##  P(X <= 80) = P(Z <= -1.333) = 0.0912
##      P(X <= 120) = P(Z <= 1.333) = 0.9088
##  P(X >  80) = P(Z >  -1.333) = 0.9088
##      P(X >  120) = P(Z >  1.333) = 0.0912

## [1] 0.09121122 0.90878878
pdist("chisq", 4, df=3)

## [1] 0.7385359
pdist("f", 3, df1=5, df2=20)

## [1] 0.9647987
qdist("t", c(.025, .975) , df=5)

## [1] -2.570582  2.570582
histogram( ~ rbinom(1000, 20, .4), width=1, v=20 * .4 )

SD <- sqrt(20 * .4 * .6)
plotDist("norm", mean=.4*20, sd=SD, add=TRUE, alpha=.7)

plotDist("norm", col="blue", mean=2, xlim=c(-4,8))
plotDist("norm", mean=5, col="green", kind='histogram', add=TRUE)  # add, overtop
plotDist("norm", mean=0, col="red", kind='histogram', under=TRUE)  # add, but underneath!

Maps

The mosaic package now provides facilities for producing choropleth maps. The API is still under developement and may change in future releases.

# we need to get state names into the data frame and then fix two of them with
# wrong state abbreviations.  Then we are ready to make maps
sAnscombe <- car::Anscombe %>%
group_by(state = rownames(car::Anscombe)) %>%
summarise(income = sum(income)) %>%
mutate(state = standardName(state, c(IO = "IA", KA = "KS"), quiet=TRUE))

mUSMap(sAnscombe, key="state", fill="income")
## Mapping API still under development and may change in future releases.

mUSMap(sAnscombe, key="state", fill="income", style="real") 
## Mapping API still under development and may change in future releases.

# A sillier example
if (require(mapproj)) {
Countries %>% mutate( nletters = nchar(gapminder) ) %>%
  mWorldMap( key="gapminder", fill="nletters") + coord_map()
} else {
Countries %>% mutate( nletters = nchar(gapminder) ) %>%
  mWorldMap( key="gapminder", fill="nletters") 
}
## Loading required package: mapproj
## Loading required package: maps
## Mapping API still under development and may change in future releases.
## Warning in standardName(x, countryAlternatives, ignore.case =
## ignore.case, : 99 items were not translated