alexarchambault/plotly-scala
Acerca de
Scala bindings for plotly.js
Herramientas de desarrolloWhat you can do
- Horizontal Bar Charts,
- Filled Area Plots,
- Sunburst Charts,
- Sankey Diagrams,
Crecimiento de estrellas medido
- in 24h
- 0
- in 7 days
- 0
- in 15 days
- -1
- in 1 month
- Recopilando historial
Cambios netos en períodos que se solapan, no totales diarios. Los datos no disponibles se dejan en blanco. Las estrellas indican interés, no calidad.
README.md
Originalplotly-scala
Scala bindings for plotly.js
plotly-scala is a Scala library able to output JSON that can be passed to plotly.js (it currently targets plotly.js 4.x). Its classes closely follow the API of plotly.js, so that one can use plotly-scala by following the documentation of plotly.js. These classes can be converted to JSON, that can be fed directly to plotly.js.
It can be used from almond, from scala-js, or from a Scala REPL like Ammonite, to plot things straightaway in the browser.
It runs demos of the plotly.js documentation during its tests, to ensure that it is fine with all their features. That allows it to reliably cover a wide range of the plotly.js features - namely, all the examples of the supported sections of the plotly.js documentation are guaranteed to be fine.
It is published for scala 2.12, 2.13, and 3 (built with the Scala 3 LTS, so that it can be used from any later Scala 3 version). On the JVM, it requires Java 11 or later.
Table of content
Quick start
From almond
Add the org.plotly-scala::plotly-almond:0.8.1 dependency to the notebook. (Latest version: )
Then initialize plotly-scala, and use it, like
//> using dep org.plotly-scala::plotly-almond:0.8.1
import plotly._
import plotly.element._
import plotly.layout._
import plotly.Almond._
val (x, y) = Seq(
"Banana" -> 10,
"Apple" -> 8,
"Grapefruit" -> 5
).unzip
Bar(x, y).plot()
(//> using directives need almond 0.14.0 or later. With earlier versions, load the dependency with
import $ivy.`org.plotly-scala::plotly-almond:0.8.1` instead.)
JupyterLab
If you're using JupyterLab, you have to install jupyterlab-plotly to enable support for rendering Plotly charts. It comes with the plotly Python package, and renders charts with its own plotly.js, that should be a 4.x one, like that of plotly 7.1 or later:
pip install "plotly>=7.1"
From scala-js
Add the corresponding dependency to your project, like
libraryDependencies += "org.plotly-scala" %%% "plotly-render" % "0.8.1"
From your code, add some imports for plotly,
import plotly._, element._, layout._, Plotly._
Then define plots like
val x = (0 to 100).map(_ * 0.1)
val y1 = x.map(d => 2.0 * d + util.Random.nextGaussian())
val y2 = x.map(math.exp)
val plot = Seq(
Scatter(x, y1).updated(name = "Approx twice"),
Scatter(x, y2).updated(name = "Exp")
)
and plot them with
val lay = Layout().updated(title = "Curves")
plot.plot("plot", lay) // attaches to div element with id 'plot'
updated, available on Scala 2 and Scala 3, returns a copy of a trace or layout element with the fields passed to it updated, and the other ones left unchanged. Unlike copy, it takes the values of optional fields as is, without wrapping them in Some(…), and several fields can be set at once, like
Layout().updated(title = "Curves", width = 600, height = 400)
Titles (title of Layout and Axis) are Title objects, written as {"text": …}, as plotly.js >= 3 expects them. A String gets converted to a Title with that text, like above. Their font or position can be set via Title.from, like Axis().updated(title = Title.from(text = "Count", font = Font(18))).
The with* setters (withName, withTitle, …) are deprecated, and only available on Scala 2. Use updated instead. The few classes with no updated method (colors, Bins, …) can be updated with copy.
From Ammonite
Load the corresponding dependency, and some imports, like
import $ivy.`org.plotly-scala::plotly-render:0.8.1`
import plotly._, element._, layout._, Plotly._
Then plot things like
val labels = Seq("Banana", "Banano", "Grapefruit")
val valuesA = labels.map(_ => util.Random.nextGaussian())
val valuesB = labels.map(_ => 0.5 + util.Random.nextGaussian())
Seq(
Bar(labels, valuesA).updated(name = "A"),
Bar(labels, valuesB).updated(name = "B")
).plot("plot.html", Layout().updated(title = "Level"))
Raw plotly.js figures
Figures can also be passed as "raw" plotly.js JSON, like what fig.to_json() returns in plotly-python, or a figure from the plotly.js documentation. This JSON is passed to plotly.js as is, so it can use any plotly.js feature, even those that plotly-scala doesn't support yet. It must be a JSON object, with data, and optionally layout, config, or frames, fields:
val figure =
"""{
"data": [{"type": "sankey", "node": {"label": ["A", "B", "C"]},
"link": {"source": [0, 0], "target": [1, 2], "value": [8, 4]}}],
"layout": {"title": {"text": "Flows"}}
}"""
Plot it with
// from almond
plotly.Almond.plotJson(figure)
// from Scala.js, attaching it to the div element with id 'plot'
plotly.Plotly.plotJson("plot", figure)
// or via Plotly.newPlot / Plotly.react
plotly.Plotly.react.fromJson("plot", figure)
// on the JVM, writing an HTML file and opening it in a browser
plotly.Plotly.plotJson("plot.html", figure, title = "Flows")
// or get the JavaScript plotting it in a div element with id 'plot'
plotly.Plotly.jsSnippetFromJson("plot", figure)
These methods throw an IllegalArgumentException if figure isn't a valid JSON object.
Rationale
Most high-level Javascript libraries for plotting have well designed APIs, enforcing immutability and almost relying on typed objects, although not explicitly. Yet, the few existing Scala libraries for plotting still try to mimick matplotlib or Matlab, and have APIs requiring users to mutate things, in order to do plots. They also tend to lack a lot of features, especially compared to the current high-end Javascript plotting libraries. plotly-scala aims at filling this gap, by providing a reliable bridge from Scala towards the renowned plotly.js.
Internals
plotly-scala consists in a bunch of definitions, mostly case classes and sealed class hierarchies, closely following the API of plotly.js. It also contains JSON codecs for those, based on jsoniter-scala, allowing to convert them to JSON that can be passed straightaway to plotly.js.
Having the ability to convert these classes to JSON, the codecs can also go the other way around: from plotly.js-compatible JSON to plotly-scala Scala classes. This way of going is used by the tests of plotly-scala, to ensure that the examples of the plotly.js documentation, illustrating a wide range of the features of plotly.js, can be represented via the classes of plotly-scala. Namely, the Javascript examples of the documentation of plotly.js are run inside a Rhino VM, with mocks of the plotly API. These mocks allow to keep the Javascript objects passed to the plotly.js API, and convert them to JSON. These JSON objects are then validated against the codecs of plotly-scala, to ensure that all their fields can be decoded by them. If these are fine, this gives a proof that all the features of the examples have a counterpart in plotly-scala.
Supported features
plotly-scala supports the features illustrated in the following sections of the plotly.js documentation:
- Scatter Plots,
- Bubble Charts,
- Line Charts,
- Bar Charts,
- Horizontal Bar Charts,
- Filled Area Plots,
- Time Series,
- Subplots,
- Multiple Axes,
- Histograms,
- Log Plots,
- Image,
- Pie Charts,
- Sunburst Charts,
- Treemaps,
- Sankey Diagrams,
- Contour Plots,
- 2D Histograms,
- 2D Histogram Contour Plots,
- Waterfall Charts,
- Funnel Charts,
- OHLC Charts,
- Polar Charts,
- Radar Charts,
- Wind Rose Charts,
- 3D Scatter Plots,
- 3D Line Plots.
It also supports violin and icicle traces, whose examples in the plotly.js documentation load their data from external files, so that the tests can't run them.
Some of these are illustrated in the demo page.
Adding support for extra plotly.js features
The following workflow can be followed to add support for extra sections of the plotly.js documentation:
- find the corresponding directory in the source of the plotly.js documentation. These directories can also be found in the sources of plotly-scala, under
plotly-documentation/_posts/plotly_js, if its repository has been cloned with the--recursiveoption, - enabling testing of the corresponding documentation section examples in the
DocumentationTestsclass, by adding the section directory tosubDirNames, - running the tests with
./mill -w "tests[2.13.18].test", - fixing the possible Javascript typos in the plotly-documentation submodule in the plotly-scala sources, so that the enabled JS snippets run fine with Rhino from the tests, then committing these fixes to
plotly/graphing-library-docs, - add the required fields / class definitions, and possibly codecs, to have the added tests pass.
The classes of plotly-scala are defined with the @data annotation of data-class, like
@data(optionSetters = true) final case class Foo(
a: Option[Int] = None,
@since("0.8.6")
b: Option[String] = None
)
When adding fields to an existing class, put them at the end, with default values, and annotate the first one added in a given version with @since, so that binary compatibility is maintained. On Scala 2, data-class generates the binary-compatible overloads and the deprecated with* setters (withA, withB) of these classes. On Scala 3, the data-class compiler plugin generates the binary-compatible overloads, but no setters. On both, the classes with nullOptionCopyMethodName = "updated" in their @data annotation also get an updated method. So code shared by Scala 2 and Scala 3 (in src/main/scala, or in the tests) shouldn't use the with* setters, but updated, or copy on the classes that don't have it.
About
Battlefield tested since early 2016 at Teads.tv
Released under the LGPL v3 license, copyright 2016-2019 Alexandre Archambault and contributors.
Parts based on the original plotly.js API, which is copyright 2016 Plotly, Inc.
Explorar proyectos relacionados
Cargando…