Reputation: 4717
I have a node application. I installed plotly with npm install plotly
, then in my node app script I require it:
var plotly = require('plotly')`
However, I do not know how to get the document element Id, which normally on the client side is fine to get, and can be passed to Plotly.newPlot
:
var gd = document.getElementById("myChart")
...
Plotly.newPlot(gd, traces, layout)
I have tried with jsdom
but got no luck.
Or is it better practice to keep all the plotly stuff on the front-end and just call it as:
<script src="/js/myplots.js"></script>
instead of trying to integrate with node? My intention is to render charts on the front-end
Upvotes: 2
Views: 6696
Reputation: 2534
As an alternative to nw.js, you can also depend on jsdom as the basis for plotly without browser. There is an example of that here: https://github.com/striezel/plotly-node-export-server/blob/master/export-server/ssr.js
fs.promises.readFile("./plotly-2.20.0.min.js", "utf-8")
.then(jsdomWindow.eval)
.then(() =>
jsdomWindow.Plotly.toImage(
{ data, layout, config },
{ format: "svg", imageDataOnly: true })
);
This works like a charm, but using eval
feels a bit dirty imho.
Upvotes: 1
Reputation: 424
According to plotly community,
The most solid option would be https://gist.github.com/etpinard/d27a44bd5dbee5490f20274 at the moment.
nw.js can be run headlessly on servers. See instructions here.
The above gist does not support PDF exports, but this should be easy to add using a third-party library e.g:
https://github.com/CBiX/svgToPdf.js
https://github.com/MrRio/jsPDF
or server-side e.g. using Ubuntu’s convert utility
Upvotes: 0
Reputation: 51
I know it is very late but if you still haven't figured it how. Here it is: Just use the ID name instead of query selecting it.
Plotly.newPlot("myChart", traces, layout)
Upvotes: 3
Reputation: 19
Keep the plotly JS file on the front end and render there. Just use node to prep your data and send it over.
Personally I prep the entire data
of Plotly.newPlot('myDiv', data);
in node then get client to request for it, so I can control the looks of the plot server side.
Plotly for Node (https://plot.ly/nodejs/) allows you to connect to a plotly server and display your graph online via their API (this requires an account and API key with Plotly) The exception to this is that is you / your company has plotly on-premises server running.
Plotly JS is the actual library that allows you to plot on your own server.
Only reason to install the node version is to allow code completion inside node
Upvotes: 1