FusionCharts

Create Amazing Blockchain Data Graphs & Charts in JavaScript

As the crypto boom gathers ever more momentum, many businesses around the world are jumping on the bandwagon and starting to trade and track cryptocurrencies. Even companies that want to avoid trading in this volatile market have realized that to remain competitive, they need to be open to the idea of using digital currencies to make and receive payments. For these reasons, with the growing popularity of digital currencies internationally, more and more are finding it necessary to monitor and graph data related to blockchain and cryptocurrencies. If you are a bitcoin enthusiast and interested in plotting blockchain data, FusionCharts is the right answer for you. FusionCharts is a comprehensive platform for creating stunning and beautiful data charts, graphs, and maps, that can be easily integrated into your app. Read on to find out how you can graph blockchain data (https://www.blockchain.com/charts) using FusionCharts in a Javascript client. Yo start, we’ll plot the number of bitcoin transactions added to the mempool per second.

What is the BlockChain.com API?

If you are looking for a crypto API, BlockChain.com provides a JSON feed for their charts and statistics data (https://www.blockchain.com/charts). For example, a basic blockchain query looks like this:
https://api.blockchain.info/charts/transactions-per-second?timespan=1weeks&format=json
This query returns a result that is a JSON object, with the following structure. Please note that only the first two data points are shown below for readability.
{"status":"ok",
 "name":"Transaction Rate",
 "unit":"Transactions Per Second",
 "period":"minute",
 "description":"The number of Bitcoin transactions added to the mempool per second.",
 "values":[{"x":1625444100,"y":1.4166666666666667},
           {"x":1625445000,"y":1.6166666666666667},
           ...
          ]
}
The data comes as (x,y) pairs in the “values” key.

How Does the FusionCharts BlockChain Data Graph Look?

If you are wondering what to expect when you choose a FusionCharts graph here is an example. In this instance, we have created a scatter graph of the number of bitcoin transactions added to the mempool per second. It looks like this: The graph above has several attractive features. These include:
  1. FusionCharts automatically plots the regression line, shown as a blue solid line, to show the long-term data. It also computes the linear regression model.
  2. You can customize the scatter plot colors and symbols.
  3. Users specify the x-axis ticks and tick labels.
  4. Users have 100% control over customizing the appearance and behavior of everything in the graph. This includes including the title, subtitle, axis labels, and everything else.

Steps to Create a FusionCharts BlockChain Data Graph

Creating a blockchain data graph with FusionCharts is easy. Here are the 4 easy steps you need to get going:

Step 1: Setup the Project

First, we’ll implement the project in Javascript using webpack. To begin, create a project directory called blockchainAPI. Open the command prompt and switch to the project directory. Next type the following to install webpack and FusionCharts:
npm i -D webpack-dev-server html-webpack-plugin path webpack-cli fusioncharts
Create two directories src and dist. In the src directory create a file called index.js. You can type the following at the command prompt:
mkdir src 
touch src/index.js
mkdir dist

Step 2: Configure the Project

To configure the project create a file called webpack.config.js in the main project directory. Add the following code to this file.

// webpack.config.js
const HtmlWebPackPlugin = require( 'html-webpack-plugin' );
const path = require( 'path' );
module.exports = {
   context: __dirname,
   entry: './src/index.js',
   output: {
      path: path.resolve( __dirname, 'dist' ),
      filename: 'main.js',
   },

   plugins: [
      new HtmlWebPackPlugin()
   ],
   devServer: {
       headers: {
           "Access-Control-Allow-Origin": "*",
           "Access-Control-Allow-Methods": "GET, POST, PUT, DELETE, PATCH, OPTIONS",
           "Access-Control-Allow-Headers": "X-Requested-With, content-type, Authorization"
         },
       proxy: {
         '/BlockchainAPI': {
            target: 'https://api.blockchain.info',
            pathRewrite: { '^/BlockchainAPI': 'https://api.blockchain.info/charts/transactions-per-second?timespan=1weeks&format=json'},
            changeOrigin: true,
         },
       },

     }
};
In the configuration file shown above, we have added a proxy for the blockchain.info URL to avoid any CORS error.

Step 3: Import FusionCharts Libraries

To import the FusionCharts libraries, first, open the index.js file and add the following code. This will import all FusionCharts libraries into the project.
// Include the core fusioncharts file from core
import FusionCharts from 'fusioncharts/core';

// Include the chart from viz folder
// E.g. - import ChartType from fusioncharts/viz/[ChartType]
import Scatter from 'fusioncharts/viz/scatter';

// Include the fusion theme
import FusionTheme from 'fusioncharts/themes/es/fusioncharts.theme.fusion';
You also need to create a div tag for the chart container on the main HTML page. Below the import section add the following to your index.js file:
//add the div tag for the chart container
const myDiv = document.createElement('div');
myDiv.id = 'chart-container';
document.body.appendChild(myDiv);

Step 4: Import the Data and Create the Graph

The fourth and final step is to import the blockchain data and create a JSON object for our chart. The “DataSource” key contains a nested key called “data”, which has the actual (x,y) points we want to plot. At the end of your  index.js file, add the following code:
async function main() {
    //Get the data
    let response = await fetch('/BlockchainAPI');
    let data = await response.json();
    if (response.ok){        
        renderPage(data);
    }
    else {
        alert('Error reading data from Blockchain Repository');
    }
}

//renders the html page when passed data as JSON text
function renderPage(JsonText){

    var dataSource = constructDataSource(JsonText);
    renderChart(dataSource);
}


//constructs JSON text for 'dataSource' key
function constructDataSource(blockchainJson){

    var dataset = [{
        "seriesname": "Bitcoin transactions",
        anchorbgcolor: "ff00ff",
        data: blockchainJson.values
    }];
    var category = []
    // Take around 5 transactions at equidistant points
    var len = blockchainJson.values.length;
    for (var i=0;i<len;i=i+Math.trunc(len/5)){
        category.push({x: blockchainJson.values[i].x, 
                       label: blockchainJson.values[i].x.toString(),
                       showverticalline: "1"
                       });
    } //end for

    var categories = [
    {
      verticallinedashed: "1",
      verticallinedashlen: "1",
      verticallinedashgap: "1",
      verticallinethickness: "1",
      verticallinecolor: "#000000",
      category
    }
  ];

  var dataSource = {"chart": {
        "caption": blockchainJson.description,
        "subcaption": "Data Source: https://www.blockchain.com",
        "xAxisName": "Time stamp",
        "YAxisName": blockchainJson.unit,
        "ynumbersuffix": "",
        "xnumbersuffix": "",
        "theme": "fusion",
        "showRegressionLine": "1",
        "plotToolText": "<b>$yDataValue</b> transactions at timestamp: <b>$xvalue</b>"

    }, 
    dataset, categories};    
    return dataSource;
}

// Draw the chart
function renderChart(dataSrc){

    FusionCharts.addDep(Scatter);
    FusionCharts.addDep(FusionTheme);
    //Chart Configurations
    const chartConfig = {
        type: 'scatter',
        renderAt: 'chart-container',
        width: '80%',
        height: '600',
        dataFormat: 'json',
        dataSource: dataSrc
    }

    //Create an Instance with chart options and render the chart
    var chartInstance = new FusionCharts(chartConfig);
    chartInstance.render();
}

//Call main method 
main();
That’s it! We just created a beautiful visualization of the blockchain data using FusionCharts scatter graphs.

Are There Other Ways to Create Effective BlockChain Data Visualizations?

If you are looking for the quickest and most effective ways to create BlockChain Data Visualizations, you don’t need to look any further. That is because FusionCharts comes with a complete library of beautiful plots, charts, maps, and graphs. In total, there are 100+ charts and 2000+ interactive maps you can easily integrate into your next app. You can also build impressive and effective dashboards, stunning interactive charts in addition to powerful illustrations using FusionCharts. Start integrating dashboards and interactive charts in your financial apps by downloading the trial FusionCharts Suite XT today. The source code for this app can be downloaded here. Happy coding!
Mehreen Saeed

Recent Posts

Pie Charts: A Slice of Data You Can’t Ignore

Ever had a data set that seemed more complicated than a Rubik's cube? You’re not…

3 weeks ago

Venn Diagrams: A Simple Yet Powerful Tool for Visualizing Relationships

We’ve all seen them in textbooks or presentations—those overlapping circles that simplify complex information into…

4 weeks ago

Announcing FusionCharts v4.1: Elevate Your Data Visualization Experience!

We’re excited to announce the upcoming release of FusionCharts v4.1—a groundbreaking step forward in the…

1 month ago

Bubble Maps: Visualizing Data Like Never Before

Have you ever been overwhelmed by a massive data set and wondered, "How do I…

1 month ago

Stock Charts: Mastering the Art of Visualizing Financial Data

If you’ve ever tried to make sense of the stock market, you’ve probably come across…

2 months ago

What is a Bar Chart Used For?

Imagine you’re comparing the sales performance of your top product lines across different regions, or…

3 months ago