Skip to content

Instantly share code, notes, and snippets.

@mick
Last active January 17, 2017 17:02
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mick/b5e29e962e7dda791c56b75b949718ec to your computer and use it in GitHub Desktop.
Save mick/b5e29e962e7dda791c56b75b949718ec to your computer and use it in GitHub Desktop.
Use Plotly to generate a chart from Mapbox Analytics

First your need plotly npm package, and a plotly account.

npm install plotly export PLOTLY_USERNAME=<plotly-username> export PLOTLY_APIKEY=<plotly-apikey> export MAPBOX_ACCESS_TOKEN=<your-mapbox-token>

To generate a image: curl --silent "https://api.mapbox.com/analytics/v1/accounts/<username>?period=2016-01-01,2016-04-29&access_token=$MAPBOX_ACCESS_TOKEN" | ./render-image.js > chart.png

Our just open that image in preview directly curl --silent "https://api.mapbox.com/analytics/v1/accounts/<username>?period=2016-01-01,2016-04-29&access_token=$MAPBOX_ACCESS_TOKEN" | ./render-image.js | open -a Preview.app -f

#!/usr/bin/env node
var plotly = require('plotly')(process.env.PLOTLY_USERNAME, process.env.PLOTLY_APIKEY);
var fs = require('fs');
var data = '';
process.stdin
.on('data', function(d) {
data += d;
}).on('end', function() {
generateChart(JSON.parse(data));
});
function generateChart(data) {
var trace1 = {
x: data.timestamps,
y: data.services.mapview,
type: "bar"
};
var figure = { 'data': [trace1] };
var imgOpts = {
format: 'png',
width: 1000,
height: 500
};
plotly.getImage(figure, imgOpts, function (error, imageStream) {
if (error) return console.log (error);
imageStream.pipe(process.stdout);
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment