GGBunch

GGBunch allows to show a collection of plots on one figure. Each plot in the collection can have arbitrary location and size. There is no automatic layout inside the bunch.

In [1]:
%useLatestDescriptors
%use lets-plot

@file:DependsOn("org.apache.commons:commons-math3:3.6.1")
In [2]:
import kotlin.random.Random
import org.apache.commons.math3.distribution.MultivariateNormalDistribution
In [3]:
val cov : Array<DoubleArray> = arrayOf(doubleArrayOf(1.0, 0.0),
                                        doubleArrayOf(0.0, 1.0))
val means : DoubleArray = doubleArrayOf(0.0, 0.0)
val xy = MultivariateNormalDistribution(means, cov).sample(400)

val xs = xy.map { it[0] }
val ys = xy.map { it[1] }

View this data as a scatter plot and as a histogram

In [4]:
val p = letsPlot() + ggsize(600,200)

val scatter = p + geomPoint(color="black", alpha=.4) {x=xs; y=ys}
scatter
Out[4]:
In [5]:
val histogram = p + geomHistogram(fill="dark_magenta") {x=xs}
histogram
Out[5]:

Combine both plots in one figure

In [6]:
// Set scale X limits manually because of computed automatically
// the scale used by each plot would be slightly different
// and the stacked plots wouldn't be aligned.
val scale_x = scaleXContinuous(limits=-3.5 to 3.5)
GGBunch().addPlot(histogram + scale_x, 0, 0)
         .addPlot(scatter + scale_x, 0, 200)
Out[6]:

Adjust visuals of the bunch figure

In [7]:
val upper_theme = theme(axis="blank", axisText=elementText(), axisTitleY=elementText(), panelGridMajorY="blank")
val lower_theme = theme(axis="blank", axisTextY=elementText(), axisTitle=elementText())
In [8]:
GGBunch().addPlot(histogram + upper_theme + scale_x, 0, 0)
         .addPlot(scatter + lower_theme + scale_x, 0, 200)
Out[8]:

Adjust plot sizes

addPlot() method has two more (optional) parameters: width and height.

This values will override plot size earlier defined via ggsize() function.

In [9]:
GGBunch().addPlot(histogram + upper_theme + scale_x, 0, 0, 600, 100)
         .addPlot(scatter + lower_theme + scale_x, 0, 100, 600, 300)
Out[9]: