jwebsite/extras/plotly.md

114 lines
3.0 KiB
Markdown

@def hascode = true
@def hasplotly = true
# Work with Plotly
If you want interactive plots on some pages and are not afraid of using heavy javascript libraries, then [Plotly](https://plot.ly/javascript/) is a nice library.
The Julia wrapper [PlotlyJS.jl](https://github.com/sglyon/PlotlyJS.jl) can be used to generate Plotly plots.
## Pre-requisites
Download [`plotly.min.js`](https://cdn.plot.ly/plotly-latest.min.js) saving it to `/_libs/plotly/plotly.min.js`.
Then create a variable `hasplotly` with default value `false`: in your `config.md` write
```
@def hasplotly = false
```
Finally, in your `src/_layout/head.html` add
```html
{{if hasplotly}} <script src="/libs/plotly/plotly.min.js"></script> {{end}}
```
## Offline-generated plot
Assuming you already have the Plotly code for some plot, displaying the result on a page with Franklin is now pretty straightforward.
Start by adding
```
@def hasplotly = true
```
so that the JS library will be loaded then somewhere appropriate add:
```html
~~~
<div id="tester" style="width:600px;height:350px;"></div>
<script>
TESTER = document.getElementById('tester');
Plotly.plot( TESTER, [{
x: [1, 2, 3, 4, 5],
y: [1, 2, 4, 8, 16] }], {
margin: { t: 0 } } );
</script>
~~~
```
This will give:
~~~
<div id="tester" style="width:600px;height:350px;"></div>
<script>
TESTER = document.getElementById('tester');
Plotly.plot( TESTER, [{
x: [1, 2, 3, 4, 5],
y: [1, 2, 4, 8, 16] }], {
margin: { t: 0 } } );
</script>
~~~
## Live-generated plot
One step further is to use `PlotlyJS` to define a plot then pass the result to Franklin.
Start by adding `PlotlyJS` and `Random` to your environment:
```julia-repl
(myWebsite) pkg> add PlotlyJS Random
```
Then, beyond the `@def hasplotly = true`, add the following code:
`````plaintext
```julia:ex1
using PlotlyJS
z = [10 10.625 12.5 15.625 20
5.625 6.25 8.125 11.25 15.625
2.5 3.125 5. 8.125 12.5
0.625 1.25 3.125 6.25 10.625
0 0.625 2.5 5.625 10]
data = contour(; z=z)
layout = Layout(; title="Basic Contour Plot")
plt = plot(data, layout)
fdplotly(json(plt)) # hide
```
\textoutput{ex1}
`````
**Note**: the `fdplotly` is a convenience function exported by `Franklin`; it just prints the required HTML such that a plotly object gets placed. It takes the JSON string of the plot (which you can get with `json(plt)`) and takes two optional keyword arguments:
- `id`: to specify the name of the div the plotly object is associated to, it's randomly generated by default, and,
- `style` which takes a string indicating the desired CSS for the div e.g. the default is `"width:600px;height:350px"`.
The code block above gives:
```julia:ex1
using PlotlyJS
z = [10 10.625 12.5 15.625 20
5.625 6.25 8.125 11.25 15.625
2.5 3.125 5. 8.125 12.5
0.625 1.25 3.125 6.25 10.625
0 0.625 2.5 5.625 10]
data = contour(; z=z)
layout = Layout(; title="Basic Contour Plot")
plt = plot(data, layout)
fdplotly(json(plt)) # hide
```
\textoutput{ex1}