✊🏿 Black Lives Matter. Please consider donating to Black Girls Code today.

Subplots in Scala

How to create subplots in Plotly with Scala.


import co.theasi.plotly
import util.Random

val xsLeft = (0 to 100).map { i => Random.nextGaussian }
val ysLeft = (0 to 100).map { i => Random.nextGaussian }

val xsRight = (0 to 100).map { i => Random.nextDouble }
val ysRight = (0 to 100).map { i => Random.nextDouble }

val figure = RowFigure(2)
  .plot(0) { // left-hand plot
    Plot().withScatter(
      xsLeft, ysLeft,
      ScatterOptions().mode(ScatterMode.Marker).name("left"))
  }
  .plot(1) { // right-hand plot
    Plot().withScatter(
      xsLeft, ysLeft,
      ScatterOptions().mode(ScatterMode.Marker).name("right"))
  }

draw(figure, "make-subplots", writer.FileOptions(overwrite=true))
import co.theasi.plotly
import util.Random

// Left-hand side: Gaussian distributed random variates
val randomXs = (0 to 100).map { i => Random.nextGaussian }
val randomYs = (0 to 100).map { i => Random.nextGaussian }

val leftPlot = Plot()
  .withScatter(randomXs, randomYs, ScatterOptions().mode(ScatterMode.Marker))

// Gaussian PDF
def gaussian2D(x: Double, y: Double) = Math.exp(-x*x - y*y)

val xs = (-4.0 to 4.0 by 0.1).toVector
val ys = (-4.0 to 4.0 by 0.1).toVector
val zs = xs.map { x => ys.map { y => gaussian2D(x, y) } }

val rightPlot = ThreeDPlot().withSurface(xs, ys, zs)

// Figure with two subplots in a row
val figure = RowFigure(2)
  .plot(0) { leftPlot }
  .plot(1) { rightPlot }

draw(figure, "mixed-subplots", writer.FileOptions(overwrite=true))
import co.theasi.plotly
import util.Random

val xs = (0 to 100).map { i => Random.nextGaussian }
def ys = (0 to 100).map { i => Random.nextGaussian }

// Options common to all the series
val commonOptions = ScatterOptions()
  .mode(ScatterMode.Marker)
  .marker(MarkerOptions().size(5))

val figure = GridFigure(2, 3) // 2 rows, 3 columsn
  .plot(0, 0) { Plot().withScatter(xs, ys, commonOptions.name("top-left")) }
  .plot(0, 1) { Plot().withScatter(xs, ys, commonOptions.name("top-middle")) }
  .plot(0, 2) { Plot().withScatter(xs, ys, commonOptions.name("top-right")) }
  .plot(1, 0) { Plot().withScatter(xs, ys, commonOptions.name("bottom-left")) }
  .plot(1, 1) { Plot().withScatter(xs, ys, commonOptions.name("bottom-middle")) }
  .plot(1, 2) { Plot().withScatter(xs, ys, commonOptions.name("bottom-rigth")) }


draw(figure, "subplots-grid", writer.FileOptions(overwrite=true))