How AnyChart uses JavaScript to create bubble charts to visualize election results

AnyChart is a chart control based on JavaScript (HTML5). Use the AnyChart control to create cross-browser and cross-platform interactive charts and gauges. AnyChart charts are currently used by many well-known large companies and can be used in dashboards, reports, data analysis, statistics, finance and other fields.

Click to download the official version of AnyChart

Insert picture description here

In today's era of exponential growth in data, visualization is an essential skill in the toolbox. Popular techniques include bar graphs, line graphs, pie charts, and bubble graphs.

For any developer, especially developers who are just starting out, building interactive charts from scratch using JavaScript can be a daunting task. This is why we have a JS chart library, which makes it easier and faster for you to create insightful visualizations!

Read on to learn how to create JavaScript bubble charts using one of these libraries.

JavaScript chart library

There are many great JavaScript libraries available, and each library has its own advantages and disadvantages. But the best part is that the process of building a chart using all charts is almost similar. Therefore, you can learn ropes with anyone and then use any library that suits your specific project requirements.

I decided to use the AnyChart JavaScript library in conjunction with this tutorial to create bubble charts. I think this is a good choice for developers with beginner to intermediate coding skills. AnyChart has a wealth of documentation, is very flexible, and has a variety of chart types, which can start your visualization journey.

What is a bubble chart and what will it display?

I know you are happy to start creating visualization files, but before we start, it is important to understand the type of chart and why it is suitable for what we want to display.

A bubble chart is essentially a combination of a bubble chart and a chart that draws bubbles on a geographic area. The size of the bubble indicates the value of a specific variable, and the location on the map indicates the location.

One of the most important events in 2020 is the US presidential election. Of course, we know the overall result. But wouldn’t it be interesting to see who wins in which state and percentage from just one point of view? Of course I think so! Although I'm sure that many of us have seen many maps of the 2020 US election, I will create my own map and show you step by step!

I will use a bubble chart, which will draw a bubble chart on each U.S. state. The 3 parameters indicated are as follows:

The number of votes in each state’s election, in units of bubble size.
The winner of each state is represented by the color of the bubble.
The percentage of votes won by opaque colors.
As you can see, the super power of the bubble chart is the ability to display multiple parameters in a single view.

Create a bubble chart using JavaScript

Now that you know what a bubble chart is and want you to be sure that it is the correct chart that represents the results of the states in the US general election, let us delve into the process.

1. Create a basic HTML page

The first step is to create a blank HTML page. In order to save my chart, I added a div element with a unique ID, which will be used to refer to it in the future.

I set the width and height of the placeholder div to 100% so that the chart is displayed on the entire screen. You can keep these values ​​according to your preferences.

Bubble Map
**2. Include the necessary scripts** The next step is to link the corresponding JS scripts that will be used to create the bubble chart. Since I am using the AnyChart library, I will quote the corresponding file. For my chart, I need to add AnyChart's Base and Geo Maps modules. I also need to include a file with geographic data for each state in the United States, which can also be found in the library's CDN.

Remind you that all script files must be included in the section of the HTML page.

3. Connecting data
There are a large number of data sets on the results of the US elections. For this chart, we need specific fields, so I have to create the final data set by combining data from multiple sources. I used the data set on the number of votes in the state elections on the website of the Library of Congress and the winner data of the Associated Press.

The AnyChart library supports many data formats, including CSV, JSON, XML... To make this easier, I preprocessed the data to include the relevant fields of the chart, as shown below:
State code,
latitude,
longitude,
state name,
electoral votes,
victory party
Percentage of votes won
Before we start using the data, we need to add 2 more script files to the HTML page. The data adapter module handles the loading of data files, so we include it. Since we are creating a map, we will use another JavaScript library, Proj4js, which converts point coordinates from one coordinate system to another. In short, it will be responsible for drawing bubbles on various geographic areas.
4. Add code to draw the chart

Now that the preliminaries are over, it's time to enter the main part. The important thing about using the JavaScript chart library is that the amount of code that must be written is really small. I will guide you through the lines of code so that you can better understand how the bubble chart is drawn.

First, I will make sure that all the code used to create the chart is inside the anychart.onDocumentReady() function. This is to fully load the page before performing any other operations. Next, we use the anychart.data.loadJsonFile() function to load the data.

I first create a map, define some settings for it, and then set up geographic data. I also added a title to the map.
anychart.onDocumentReady (function () { anychart.data.loadJsonFile ( 'https://gist.githubusercontent.com/shacheeswadia/70ec3d69e0e7a8bff7917607ea2926e4/raw/c3329fa81e86d9e637503b042becd17e68d9a718/bubbleMapData.json', function (Data) {


        // Creates map chart
        var map = anychart.map();

        // Define settings for maps regions
        map
          .unboundRegions()
          .enabled(true)
          .fill('#E1E1E1')
          .stroke('#D2D2D2');

        // Set geodata using the script added
        map.geoData('anychart.maps.united_states_of_america');

        // Set Chart Title
        map
          .title('2020 US Election Results');
       
    });
  });

Next, I add bubbles to the map. Since tiny bubbles cannot be seen well, and large bubbles will cause chaotic overlap, I set the minimum and maximum bubble size.
// Set bubble min/max size settings
map.minBubbleSize('0.8%').maxBubbleSize('5%');
Now, since we want to display the election results, we need to use the color of the winning party to represent each state The winner-the Democratic Party represents blue, and the Republican Party represents red. To do this, we check the winner in the data and assign the corresponding color to the fill attribute.
// Fill color based on the winner
data.forEach(function(d){ if(d.winner == “Democrats”){ d.fill = “#019bd8”; }else{ d.fill = “#d81c28”; } }); Then, I draw a bubble based on the data and set the size of the bubble to reflect the number of election votes in the data. I enabled the default tooltips and labels of the bubble chart through some styles. The final step is to set up the container to reference the previously added HTML block element and draw the chart.







That's it-just use these few lines of HTML and JS code to prepare a beautiful, fully functional interactive bubble chart!

You can check out this initial version on CodePen [or on the Playground]. For your convenience, here is the complete code:

<script src="https://cdn.anychart.com/releases/v8/js/anychart-data-adapter.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/proj4js/2.3.15/proj4.js"></script>

<style type="text/css">

  html,
  body,
  #container {
    width: 100%;
    height: 100%;
    margin: 0;
    padding: 0;
  }

</style>
</head>
<body>

<div id="container"></div>

<script>

  anychart.onDocumentReady(function () {
    anychart.data.loadJsonFile(
      'https://gist.githubusercontent.com/shacheeswadia/70ec3d69e0e7a8bff7917607ea2926e4/raw/c3329fa81e86d9e637503b042becd17e68d9a718/bubbleMapData.json',
      function (data) {

        // Creates map chart
        var map = anychart.map();

        // Define settings for maps regions
        map
          .unboundRegions()
          .enabled(true)
          .fill('#E1E1E1')
          .stroke('#D2D2D2');

        // Set geodata using the script added
        map.geoData('anychart.maps.united_states_of_america');

        // Set Chart Title
        map
          .title('2020 US Election Results');

        // Set bubble min/max size settings
        map.minBubbleSize('0.8%').maxBubbleSize('5%');

        // Fill color based on the winner
        data.forEach(function(d){
          if(d.winner == "Democrats"){
            d.fill = "#019bd8";
          }else{
            d.fill = "#d81c28";
          }
        });

        //Charting the bubbles
        var series = map.bubble(
          anychart.data.set(data).mapAs({ size: 'electoralvotes' })
        );

        // Tooltip
        series
          .tooltip(true)
          .stroke('2 #E1E1E1')
          .fill('#1976d2')
          .selectionMode('none');

        // Labels
        series
          .labels()
          .enabled(true)
          .anchor('left-center')
          .position('right')
          .fontSize(11)
          .offsetX(5);

        // Set container id for the chart
        map.container('container');

        // Initiates chart drawing
        map.draw();
        
    });
  });

Custom bubble chart

JS chart library usually provides a series of pre-built customization options.

The existing bubble chart is already great, but we can adjust it with more code to make it more insightful, beautiful, and improve the information displayed.

A. Distribution of opacity based on votes

Without adding too much complexity, it is always a good idea to display the maximum information in one view. Therefore, I want to add a new aspect to the visualization by using the opacity of the bubble color to indicate the percentage of votes won. This will be a great opportunity to show you how to use different JavaScript libraries in the process. You need some specific functions.

I will use D3.js (a well-known open source JS library for data graphics) and use it to create a linear scale that will accept the value of the voting percentage in the data and return the corresponding opacity value. For this, I added the necessary D3 script, and then added the code to zoom. I adjust the input and output values ​​according to the data. Finally, I add the opacity value to the fill attribute.
// Linear scale to get opacity values
var opacity = d3.scaleLinear()
.domain([49, 70])
.range([0.4, 0.9]);

// Fill color based on winner and opacity based on% of votes won
data.forEach(function(d){ var opacityVal = opacity(d.votepercent); opacityVal = opacityVal.toFixed(2); if(d.winner == "Democrats"){ d.fill = "#019bd8 "+ opacityVal; }else{ d.fill = "#d81c28" + opacityVal; } }); If you don’t fully understand this part, please don’t feel overwhelmed. You will find that although it is slightly beyond the level of beginners, it is still helpful for many people and is not too complicated.








B. Improve tooltips

The default tooltip only displays the name of the state, whose latitude/longitude and value correspond to the number of electoral votes in each state.
We can customize the tooltip to display the information we want to display-more meaningful.

For each state, I decided to display the name of the winner, the number of electoral votes and the percentage of votes received by the winner. Since I want to display multiple fields, I enabled HTML for the tooltip, which allows me to format the text. Then, I add all the information and modify some styles in HTML format. Well, now tooltips are like a constructive addition to bubble chart visualization.
// Enable HTML for labels
series.tooltip().useHtml(true);

// Customize tooltip text
series
.tooltip()
.titleFormat("

{%name}")
.format(“
Winning Party: {%winner}
Electoral Votes: {%electoralvotes}
% of votes won: {%votepercent}%
”);

C. Enhance the overall appearance of the chart

Finally some simple modifications to enhance the chart. I added some styled captions to the chart and changed the label color to make it more contrasting.

The last thing I want to adjust is the color of the bubble when hovering over it.

Look! We have a fascinating and effective bubble chart visualization based on JavaScript that can display US election results data by state!

in conclusion

As you can see, it is very easy and exciting to use JavaScript libraries to create interactive data visualizations (such as bubble charts). You can research other JavaScript chart libraries and find more information about them.

I hope this tutorial has made you interested in data visualization and excited you to start exploring JavaScript charts. Please feel free to ask any questions, provide suggestions or leave comments. All in all, don't wait to start creating beautiful, useful visualizations!

Related product recommendation:
AnyGantt- an ideal tool for building complex and rich Gantt charts

AnyMap- interactive map is AnyChart component

AnyStock-Flash financial chart solution based on XML/JSON

APS helps improve the production efficiency of enterprises, truly realize the visual presentation and control of production plans, quickly and effectively respond to production plans in different scenarios, improve on-time delivery capabilities, and increase production capacity and resource utilization.

Guess you like

Origin blog.csdn.net/RoffeyYang/article/details/113599694