Black Lives Matter. Please consider donating to Black Girls Code today.
Learn how to use COVID-19 data in open source Dash apps. Register for the Sept 23rd webinar with IQT!

Node.js getImage problem

I’m trying to generate a pie chart and pipe it to a png file using plotly.getImage. My node.js file looks like this:

var plotly = require(‘plotly.js’)(‘username’, ‘apiKey’);
var fs = require(‘fs’);

var data = [
{ labels: [ ‘Ability’, ‘Primary’, ‘Special’, ‘Heavy’ ],
values: [ 18168, 34686, 8490, 3362 ],
type: ‘pie’ }
];

var layout = { title: ‘Plot Title’ };

var chart = { ‘data’: [ data ], ‘layout’:layout };

var pngOptions = { format: ‘png’, width: 1000, height: 500 };

plotly.getImage(chart, pngOptions, function (err, imageData) {
if (err) throw err;

var pngStream = fs.createWriteStream('test.png');
imageData.pipe(pngStream);

});

/*
plotly.plot(data, layout, function (err, msg) {
if (err) throw err;

console.log(msg);

});
*/

I’m getting the following error:

/Users/jachal/Documents/workspace/statbot/node_modules/plotly.js/src/lib/is_plain_object.js:19
if(window && window.process && window.process.versions) {
^

ReferenceError: window is not defined
at isPlainObject (/Users/jachal/Documents/workspace/statbot/node_modules/plotly.js/src/lib/is_plain_object.js:19:8)
at _extend (/Users/jachal/Documents/workspace/statbot/node_modules/plotly.js/src/lib/extend.js:92:40)
at exports.extendDeep (/Users/jachal/Documents/workspace/statbot/node_modules/plotly.js/src/lib/extend.js:34:12)
at makeColorScaleAttributes (/Users/jachal/Documents/workspace/statbot/node_modules/plotly.js/src/components/colorscale/color_attributes.js:28:21)
at Object. (/Users/jachal/Documents/workspace/statbot/node_modules/plotly.js/src/traces/scatter/attributes.js:305:13)
at Module._compile (module.js:573:32)
at Object.Module._extensions…js (module.js:582:10)
at Module.load (module.js:490:32)
at tryModuleLoad (module.js:449:12)
at Function.Module._load (module.js:441:3)

What am I doing wrong?

You’re requiring plotly.js here, NOT the nodejs api plotly.

See https://github.com/plotly/plotly-nodejs#installation

Oh boy! That’s embarrassing!

I’ve corrected my oversight and appreciate the assistance. I am now able to generate the test file, however, it is not matching my expected output. I get the plot attached instead of the pie chart.

Your data value is doubly-nested:

var data = [
{ labels: [ 'Ability', 'Primary', 'Special', 'Heavy' ],
values: [ 18168, 34686, 8490, 3362 ],
type: 'pie' }
];

should be

var trace = { 
  labels: [ 'Ability', 'Primary', 'Special', 'Heavy' ],
  values: [ 18168, 34686, 8490, 3362 ],
  type: 'pie' 
}

var chart = { 'data': [trace] }

Fantastic! I really appreciate your assistance!!!

1 Like