This page is available as an executable or viewable Jupyter Notebook:



In [1]:
%useLatestDescriptors
%use lets-plot
%use numpy
In [2]:
import org.jetbrains.numkt.core.*
import org.jetbrains.numkt.math.*
import org.jetbrains.numkt.random.Random
import org.jetbrains.numkt.*
In [3]:
val cov0 = array<Double>(listOf(listOf(1, -.8),
                                listOf(-.8, 1)))
val cov1 = array<Double>(listOf(listOf(1, .8),
                                listOf(.8, 1)))
val cov2 = array<Double>(listOf(listOf(10, .1),
                                listOf(.1, .1)))

val n = intArrayOf(400)
val xy0 = Random.multivariateNormal(mean=array(listOf(-2,0)), 
                                    cov=cov0, 
                                    size=n,
                                    checkValid="raise",
                                    tol=1e-8
                                   ).transpose()
val xy1 = Random.multivariateNormal(mean=array(listOf(2,0)), 
                                    cov=cov1, 
                                    size=n,
                                    checkValid="raise",
                                    tol=1e-8
                                   ).transpose()
val xy2 = Random.multivariateNormal(mean=array(listOf(0,1)), 
                                    cov=cov2, 
                                    size=n,
                                    checkValid="raise",
                                    tol=1e-8
                                   ).transpose()
In [4]:
val data = mapOf(
    "x" to concatenate(xy0[0], xy1[0], xy2[0]).toList(),
    "y" to concatenate(xy0[1], xy1[1], xy2[1]).toList()
)
In [5]:
val p = letsPlot(data) {x="x"; y="y"} + ggsize(600,300) +
        geomPoint(color="black", alpha=.1)
p
Out[5]:
In [6]:
// Basic density 
p + geomDensity2D(color="red")
Out[6]:
In [7]:
// Set contour color by level
//  - change defailt position and size of colorbar
p + geomDensity2D {color="..level.."} +
    scaleColorGradient(low="dark_green", high="yellow", guide=guideColorbar(barHeight=10, barWidth=300)) +
    theme().legendPosition_bottom()
Out[7]:

Filling contours by level

In [8]:
val p1 = letsPlot(data) {x="x"; y="y"} + ggsize(600,300)

// Filled polygons are not always working well - note missing polygons in the middle. 
p1 + geomPolygon(stat=Stat.density2D()) {fill="..level.."} + coordFixed()
Out[8]: