Github style contribution graph for displaying the activity in your website using Node.js,Express.js,D3.js,Mongodb .
This article will help you create a github style graph to represent purchase data from your application. With simple modification, you can represent user activity etc in this format.
Well what is Github style ?
Image is worth a thousand words!
Increase in shades of green if more contributions done by user.Darkest green being the best.
Now,lets get a similar graph which shows the orders made through year 2017.Show simple details as to purchases when hovered on a cell meant for a specific day.
How is it helpful ?
- At one glance get an idea of the orders.Show color based on the total order amount per day.
- You would get an idea if your campaings are working well if during the campaign and later you see a flurry of activity .
How will the final project look ?
Lets look at how we will achieve this
Step1 : Get data into Mongo .
You can use data from your data source .For the purpose of this article,I have created some random data and placed it in the mlab database . Mlab is a cloud mongo database. More details to get started here.
Step2: Aggregate values from database to get total order amount per day.
Orders.aggregate(
[
{
'$project': {
createdOn: {'$dateToString': {format: '%Y-%m-%d', date: '$Date'}},
price:1
}
},
{
$group: {
_id: "$createdOn",
totalprice: { $sum: "$price" }
}
}
]
Project the date with changed date format and use that to aggregate the total order amount.
Process the results to store in a javascript object so that we can search the total order amount per each day.While using decimal values from mongodb , use parseFloat to get the value for use .
datesTable[obj._id] = (parseFloat(obj.totalprice));
Pass this to the index.pug file ,which renders the graph.The rest of the processing happens in the client side.
Step 3: Index.pug file.
Here we sort the total order value per day and find quantiles .For each threshold,we assign a color. the color class determined by the value is added as a class to the grid cell.
var domainArray = [d3.quantile(dataArray, 0.25),d3.quantile(dataArray, 0.5),d3.quantile(dataArray, 0.65),d3.quantile(dataArray, 0.75),d3.quantile(dataArray, 0.85),d3.quantile(dataArray, 0.95),d3.quantile(dataArray, 1)];var formatColor = d3.scaleThreshold().domain(domainArray).range(d3.range(NUMBER_OF_COLORS).map((d) => `color${d}`));
The github style code is heavily adapted from https://github.com/vinnyoodles/reddit-heatmap .
Please go through the entire code to get more idea. Here’s the github link .
Hope you found this article useful .If so, please clap .
Follow me to receive more articles in Node n Javascript which will definitely be helpful.
If you like this article ..you might be interested in