Search code examples
chart.jscanvasjs

How to use canvasjs to draw column chart using text data


I am using the canvasjs for plotting the column chart. I am using the code from this link https://canvasjs.com/editor/?id=https://canvasjs.com/example/gallery/column/oil_reserves/, the code is below:

 <!DOCTYPE HTML>
 <html>
 <head>  
 <title>Basic HTML5 Column Chart </title>
 <script type="text/javascript">
 window.onload = function () {
 var chart = new CanvasJS.Chart("chartContainer",
  {
  title:{
    text: "Top Oil Reserves"    
  },
  animationEnabled: true,
  axisY: {
    title: "Reserves(MMbbl)"
  },
  legend: {
    verticalAlign: "bottom",
    horizontalAlign: "center"
  },
  theme: "theme2",
  data: [

  {        
    type: "column",  
    showInLegend: true, 
    legendMarkerColor: "grey",
    legendText: "MMbbl = one million barrels",
    dataPoints: [      
    {y: 297571, label: "Venezuela"},
    {y: 267017,  label: "Saudi" },
    {y: 175200,  label: "Canada"},
    {y: 154580,  label: "Iran"},
    {y: 116000,  label: "Russia"},
    {y: 97800, label: "UAE"},
    {y: 20682,  label: "US"},        
    {y: 20350,  label: "China"}        
    ]
  }   
  ]
});

chart.render();
}
</script>
 <script type="text/javascript" src="https://canvasjs.com/assets/script/canvasjs.min.js"></script>
 </head>
 <body>
 <div id="chartContainer" style="height: 300px; width: 100%;">
 </div>
 </body>
 </html>

Now I want to use a text file generated from python instead of the default values in the dataPoints. The test file data looks like a dictionary data separated by comma. Here is a sample of the text file data:

     {'DNS_SERVER1': 2.768651, 'FTP_SERVER1': 2.488129, 'AUTHENTICATION_SERVER1': 2.768651, 'WAP_SERVER1': 2.768651, 'WEB_SERVER1': 2.768651, 'EMAIL_SERVER1': 2.768651}

I want the labels to be first part before semicolon like 'DNS_SERVER1' and the value y to be equal to 2nd part of the semicolon like 2.768651. How Can I do this using the canvasjs script? Any help is appreciated.

Thanks.


Solution

  • You must have to read the file to two separate datasets (LABELS and DATA) and insert them like this:

      data = {
              labels: ["DNS_SERVER", "FTP_SERVER", "AUTH_SERVER"],
              datasets: [{
                 label: 'Performance',
                  data: [2.768651, 2.488129, 2.768651]
                        }]
             };
    

    Above is a nominal way. You can change "labels:" dataset and "data:" dataset for your loaded data.