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

Jason Melton
2 min readApr 22, 2020

--

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.

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.

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.’

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.

--

--

Jason Melton
Jason Melton

No responses yet