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



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

import kotlin.math.*
In [2]:
// This example was found at: 
// https://jakevdp.github.io/PythonDataScienceHandbook/04.04-density-and-contour-plots.html

val x = arange<Double>(0, 5, 6.0/50)
val y = arange<Double>(0, 5, 6.0/40)
val grid = meshgrid(x, y)
In [3]:
// @org.jetbrains.numkt.core.ExperimentalNumkt
// fun f(x:KtNDArray<Double>, y:KtNDArray<Double>): KtNDArray<Double> {
//     return sin(x) `**` 10 + cos(10 + y * x) * cos(x)
// }

fun f(x:Double, y:Double): Double {
    return sin(x).pow(10) + cos(10 + y * x) * cos(x)
}
val X = grid[0].reshape(-1).toList()
val Y = grid[1].reshape(-1).toList()
val Z = X.zip(Y).map {f(it.first,it.second)}
In [4]:
val p = lets_plot {x=X; y=Y; fill=Z}
p + geom_tile() + scale_fill_hue()
Out[4]:
In [5]:
// Lets use greyscale and also remove colorbar.
val p1 = p + geom_tile(alpha=.5) + scale_fill_grey(1, .2, guide="none")
p1
Out[5]:
In [6]:
// Add contours
p1 + geom_contour(color="red") {z=Z}
Out[6]:
In [7]:
// Set contour color by level
p1 + geom_contour {z=Z; color="..level.."} + scale_color_gradient(low="dark_green", high="yellow")
Out[7]:

Filling contours by level

In [8]:
val p2 = ggplot {x=X; y=Y}

// Filled polygons are not working very well in this case
p2 + geom_polygon(stat=Stat.contour {z=Z}) {fill="..level.."}
Out[8]:
In [9]:
// 'contourf' geom works a lot better:
p2 + geom_contourf {z=Z; fill="..level.."}
Out[9]: