Using Chart.js to Create Tug-Of-War-like Graphs

Image for post
Image for post

During coding bootcamp, my partner David and I created an A/B polling app called “This Or That”. The app allows users to create simple two option polls and vote on any polls published on the page.

“This or That” was fun to code and use. You could compare any two options — Jordan vs. Lebron, Root Beer vs. Pink Lemonade, Jason Is the Greatest vs. Yes He Is. Your imagination is the limit.

I really wanted to add a visual component to show off during our upcoming presentation. Me and David discussed how we’d like a graph show the votes and discussed a similar graph feature we had seen on Instagram.

Image for post
Image for post

We wanted to emulate this for our project. Once an option is selected, the graph should display the current statistics of options. I searched google for a solution and Chart.js was the top result.

Image for post
Image for post

Chart.js is a popular and relatively simple code library for creating all kinds of charts. I installed it with npm and experimented with various pie charts and bar graphs. I got the feel for its syntax — especially by inspecting samples. From there, I was able to pull from the sample charts to customize the perfect (what I now know is a) ‘stacked horizontal bar graph.’

Image for post
Image for post
B ekes out A by one vote

After installing and setting up Chart.js in my project, here’s my code for the chart above:

Not shown above: charts must be embedded in canvas elements. Line 1 points the variable 'ctx' at one.

I encourage anyone interested in making a chart like this — or really any chart, check out Chart.js. It was an incredibly useful tool for this project.

Written by

Software dev. Love root beer.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store