Permalink
Browse files

Return some application/vnd.plotly.v1+json data too

So that plotly-scala works from nteract
  • Loading branch information...
alexarchambault committed Oct 23, 2018
1 parent 19fe832 commit 14aa37ad79d1f687c413c56dd513b134e0870b5e
Showing with 42 additions and 20 deletions.
  1. +31 −19 almond/src/main/scala/plotly/Almond.scala
  2. +11 −1 render/jvm/src/main/scala/plotly/Plotly.scala
@@ -2,7 +2,7 @@ package plotly
import java.lang.{Boolean => JBoolean, Double => JDouble, Integer => JInt}
import almond.interpreter.api.OutputHandler
import almond.interpreter.api.{DisplayData, OutputHandler}
import scala.util.Random
import plotly.element._
@@ -50,25 +50,48 @@ object Almond {
</script>
"""
Internal.initialized = true
publish.html(html)
}
def plotJs(
div: String,
data: Seq[Trace],
layout: Layout
layout: Layout,
div: String = ""
)(implicit
publish: OutputHandler
): Unit = {
): String = {
val (div0, divPart) =
if (div.isEmpty) {
val d = randomDiv()
(d, s"""<div class="chart" id="$d"></div>""")
} else
(div, "")
val baseJs = Plotly.jsSnippet(div, data, layout)
val baseJs = Plotly.jsSnippet(div0, data, layout)
val json = Plotly.jsonSnippet(data, layout)
val js =
s"""requirejs(["plotly"], function(Plotly) {
s"""require('plotly', function(Plotly) {
| $baseJs
|});
""".stripMargin
publish.js(js)
val data0 = DisplayData(
data = Map(
"text/html" ->
s"""$divPart
|<script>$js</script>
""".stripMargin,
"application/vnd.plotly.v1+json" -> json
)
)
publish.display(data0)
div0
}
def randomDiv() = "plot-" + math.abs(Random.nextInt().toLong)
@@ -89,18 +112,7 @@ object Almond {
}
}
val div0 =
if (div.isEmpty)
randomDiv()
else
div
if (div.isEmpty)
publish.html(s"""<div class="chart" id="$div0"></div>""")
plotJs(div0, data, layout)
div0
plotJs(data, layout)
}
implicit class DataOps(val data: Trace) extends AnyVal {
@@ -9,7 +9,7 @@ import java.lang.{Boolean => JBoolean, Double => JDouble, Integer => JInt}
import java.nio.file.Files
import argonaut.Argonaut._
import argonaut.PrettyParams
import argonaut.{Json, PrettyParams}
import plotly.internals.{BetterPrinter, Properties}
import scala.annotation.tailrec
@@ -18,6 +18,16 @@ object Plotly {
private val printer = BetterPrinter(PrettyParams.nospace.copy(dropNullKeys = true))
def jsonSnippet(data: Seq[Trace], layout: Layout): String = {
val json = Json.obj(
"data" -> data.toList.asJson,
"layout" -> layout.asJson
)
printer.render(json)
}
def jsSnippet(div: String, data: Seq[Trace], layout: Layout): String = {
val b = new StringBuilder

0 comments on commit 14aa37a

Please sign in to comment.