How to Create an Interactive Diverging Bar Chart with JavaScript

Diverging bar charts are an effective way to visualize data with both positive and negative values, or that diverges from a central baseline. Some examples of data well-suited for this type of chart include:

  • Survey results showing the percentage of respondents who agree vs disagree with a statement
  • Temperatures above and below a comfortable room temperature range
  • Spending vs budget amounts by category
  • Sentiment analysis showing counts of positive and negative reviews

The bars extend bi-directionally from a center line to show the magnitude of values in two opposing directions. This makes it easy to compare the relative differences between categories on either side of the center point.

In this tutorial, I‘ll walk through how to build an interactive diverging bar chart using JavaScript. We‘ll visualize some political data on the 2020 U.S. presidential election, showing the number of Democratic and Republican votes cast in each state.

Here‘s a preview of the finished diverging bar chart we‘ll create:

Final interactive diverging bar chart of 2020 US election votes by state

Let‘s jump in and learn how to make this engaging data visualization!

Overview of Steps

At a high level, here are the steps to create a diverging bar chart with JavaScript:

  1. Set up a basic HTML page with a

    element to contain the chart.

  2. Include the necessary JavaScript files, usually from a charting library‘s CDN.

  3. Prepare the data that will be visualized in the proper format.

  4. Write JavaScript code to render the chart, specifying the chart type, data, and customizations.

We‘ll use the popular open-source AnyChart library for this example, but the same general process applies for other JS charting libraries like D3.js, Chart.js, or Highcharts. The exact syntax will just be a bit different.

Step 1: Set up the HTML Page

First, create a blank HTML page and add a

element that will serve as a container for the diverging bar chart. Give it a unique id so we can reference it later in the JavaScript code.

<html>
  <head>
    <title>JavaScript Diverging Bar Chart</title>
    <style type="text/css">      
      html, body, #container { 
        width: 100%; height: 100%; margin: 0; padding: 0; 
      } 
    </style>
  </head>
  <body>  
    <div id="container"></div>
  </body>
</html>

The CSS in the block ensures the chart will fill the entire page. You can set specific width and height values in pixels too.

Step 2: Include JavaScript Files

Next, we need to include the JavaScript files for the charting library. For AnyChart, there is a base module that provides core functionality. Additional modules offer different chart types and features.

Copy the following tag and place it in the section of your HTML page:

<script src="https://cdn.anychart.com/releases/8.11.0/js/anychart-base.min.js"></script>

This loads the AnyChart base module from their CDN. You can also download the file to host it yourself.

Step 3: Prepare the Data

Now let‘s get the data ready to be visualized in the diverging bar chart. We‘ll use data from the 2020 United States presidential election that shows the total votes cast for the Democratic and Republican candidates in each state.

Here‘s a snippet of the data, with values rounded to the nearest thousand:

var electionData = [
  {state: "California", dem: 11110000, rep: 6006000},
  {state: "Texas", dem: 5259000, rep: 5890000},
  {state: "Florida", dem: 5297000, rep: 5669000},
  {state: "New York", dem: 5230000, rep: 3245000},
  // more states...
];

Each row is an object with properties for the state name and votes for the Democratic and Republican candidates.

We‘ll put this data in a JavaScript variable inside a block at the end of the HTML page, right before the closing tag:

  <script>
    var electionData = [
      // ... data here
    ];
  </script>
</body>
</html>

Step 4: Render the Chart

Finally, we‘re ready to write the JavaScript code that will render the interactive diverging bar chart!

First, add opening and closing tags after the code for the data variable:

<script>
  var electionData = [
    // ... data here 
  ];

  // chart code will go here

</script>

All of our chart code will go inside these script tags. To start, we use the anychart.onDocumentReady function and put the rest of the code inside it. This ensures that our chart is only drawn once the page finishes loading.

anychart.onDocumentReady(function () {

  // The rest of the chart code goes here

});  

Next, create the diverging bar chart itself by calling the anychart.bar() function and saving it to a variable:

var chart = anychart.bar();

To convert our election data into the format needed by AnyChart, we map over the rows and return an array with values for each bar‘s state name, Democratic votes (negative), and Republican votes (positive):

var data = electionData.map(function (item) {
  return [item.state, -item.dem, item.rep];
});

chart.data(data);

Now specify the placement of bars extending left and right from the zero line:

var series1 = chart.bar(data.map(function(x) { 
  return [x[0], x[1], 0]; 
}));

var series2 = chart.bar(data.map(function(x) { 
  return [x[0], 0, x[2]];
}));

Let‘s configure the series names, colors, and add a white stroke between bars:

series1.name("Democratic Votes")
  .color("#0015BC")
  .stroke("2 #fff");  

series2.name("Republican Votes") 
  .color("#FF0000") 
  .stroke("2 #fff");

To polish the look of the diverging bar chart, we‘ll make several customizations to the axes. Format the scale so bar lengths represent vote totals in millions:

chart.yScale()
  .minimum(-15)
  .maximum(15) 
  .ticks({ interval: 5 })
  .labels({ 
     format: function (x) { return Math.abs(x) / 1000000; }
   });  

chart.yAxis().labels().format(function() {
   return Math.abs(this.value) + "M";  
});

Clean up the x-axis by removing ticks, adding a title, and formatting labels:

chart.xAxis(0)   
  .ticks(false) 
  .title()
  .enabled(true)   
  .text("States")
  .padding(5);

chart.xAxis(0).labels()  
  .fontSize(11)
  .fontColor("#474747")  
  .padding(5);

Add a custom HTML tooltip to show the state name and vote totals when hovering:

var tooltipText = 
  "<span style=‘font-size:14px; font-weight:bold‘>" +
  "{%x}</span><br>" + 
  "<span style=‘color: #0015BC‘>Democratic Votes: </span>" +
  "{%value} M<br>" +
  "<span style=‘color: #FF0000‘>Republican Votes: </span>" +
  "{%yValueRight} M";

chart.tooltip()
  .useHtml(true)  
  .format(tooltipText);

Finally, set the container id, overall chart title, and call the draw() method to render the diverging bar chart:

chart.container("container"); 

chart.title("2020 US Presidential Election Votes by State");

chart.draw();

Here‘s the full JavaScript code putting it all together:

anychart.onDocumentReady(function () {

  var chart = anychart.bar();

  var data = electionData.map(function (item) {
    return [item.state, -item.dem, item.rep];  
  });

  chart.data(data);

  var series1 = chart.bar(data.map(function(x) {
    return [x[0], x[1], 0];
  }));

  var series2 = chart.bar(data.map(function(x) { 
    return [x[0], 0, x[2]];
  }));

  series1.name("Democratic Votes")
    .color("#0015BC")
    .stroke("2 #fff");

  series2.name("Republican Votes")
    .color("#FF0000")
    .stroke("2 #fff");

  chart.yScale()
    .minimum(-15) 
    .maximum(15)
    .ticks({ interval: 5 })
    .labels({
       format: function (x) { return Math.abs(x) / 1000000; } 
    });

  chart.yAxis().labels().format(function() {
    return Math.abs(this.value) + "M";   
  });

  chart.xAxis(0) 
    .ticks(false)
    .title() 
    .enabled(true)
    .text("States") 
    .padding(5);

  chart.xAxis(0).labels()
    .fontSize(11)
    .fontColor("#474747")
    .padding(5);   

  var tooltipText =
    "<span style=‘font-size:14px; font-weight:bold‘>" + 
    "{%x}</span><br>" +
    "<span style=‘color: #0015BC‘>Democratic Votes: </span>" + 
    "{%value} M<br>" +
    "<span style=‘color: #FF0000‘>Republican Votes: </span>" +
    "{%yValueRight} M";

  chart.tooltip() 
    .useHtml(true)
    .format(tooltipText);

  chart.container("container");

  chart.title("2020 US Presidential Election Votes by State");

  chart.draw();

});

With that last line of code, you should see a beautiful diverging bar chart appear on your page! It displays the Democratic and Republican vote totals extending to the left and right for each state. Hovering over a bar brings up a tooltip with more details.

Customizing the Diverging Bar Chart

You can easily customize the appearance and behavior of the diverging bar chart by modifying the JavaScript code.

Some ideas to try:

  • Change the colors of the bars by passing different hex codes or RGB values to the .color() methods
  • Adjust the chart height and width by setting .height() and .width() on the chart
  • Modify the axis labels, ticks, and scale
  • Format the values shown on hover in the tooltip
  • Enable a click event to update the chart data or link to another page

Feel free to experiment and make the chart your own! Refer to the AnyChart documentation for more customization options.

JavaScript Libraries for Diverging Bar Charts

There are a number of great JavaScript charting libraries that support diverging bar charts. Here are a few popular ones to consider:

  • AnyChart: Robust library with 70+ chart types, including diverging bar charts. Detailed documentation and flexible API for customization. Free for non-commercial use.

  • D3.js: Powerful low-level library for data visualization. Diverging bar chart is possible but requires more code compared to higher-level charting libraries. Free open-source license.

  • Chart.js: Simple yet flexible library with built-in support for diverging bar charts (via the horizontal bar chart type). Easy setup and customization. Free open-source license.

  • Highcharts: Feature-rich library supporting diverging bar charts with many design options. Free for non-commercial use, paid plans for business use.

When evaluating JS charting libraries, consider factors like chart types offered, documentation quality, ease of use, customization options, licensing, and community support. The best fit depends on your specific needs and preferences.

Conclusion and Resources

You should now have a solid understanding of how to create an interactive diverging bar chart using JavaScript! We covered the key steps of setting up the HTML page, including the necessary JavaScript files, preparing the data, and writing the code to render and customize the chart.

The demo in this tutorial visualized 2020 U.S. presidential election data, showing Democratic and Republican vote totals diverging from the center line for each state. But diverging bar charts are useful for many other datasets too, like survey results, temperatures, financial metrics, and more.

I encourage you to practice making your own diverging bar charts with different data. Experiment with the customization options and try out several JS charting libraries to find your favorite.

Here are some helpful resources for further learning:

You can also find inspiration from diverging bar charts in the wild. Look for them in data-heavy news articles, financial reports, and analytical dashboards.

Feel free to leave a comment if you have any questions or insights to share. Happy data visualizing!

Similar Posts

Leave a Reply

Your email address will not be published. Required fields are marked *