Google API Visualization Chart Not Working

浪子不回头ぞ 提交于 2020-01-06 03:09:06

问题


I used the Google Visualization API for making 3 graphs but only 1 graph is showing. However, when I refresh the page or go to a different browser, a different graph appears. How do I make every graph appear? I used @WhiteHat suggestion but it did not work. Here is the updated code after their suggestion:

<script>
    (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
    (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
    m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
    })(window,document,'script','//www.google-analytics.com/analytics.js','ga');

    ga('create', 'UA-66892235-1', 'auto');
    ga('send', 'pageview');
</script>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="description" content="">
<meta name="author" content="">

<title>Analysis Tool</title>

{% load staticfiles %}

<!-- Bootstrap Core CSS -->
<link rel="stylesheet" type="text/css" href="{% static 'home/css/bootstrap.min.css' %}" />

<!-- Custom CSS -->
<link rel="stylesheet" type="text/css" href="{% static 'home/css/grayscale.css' %}" />
<link rel="stylesheet" type="text/css" href="{% static 'home/css/style.css' %}" />
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>

<!-- Custom Fonts -->
<link href="{% static 'home/font-awesome/css/font-awesome.min.css' %}" rel="stylesheet" type="text/css">

<link href="http://fonts.googleapis.com/css?family=Lora:400,700,400italic,700italic" rel="stylesheet" type="text/css">
<link href="http://fonts.googleapis.com/css?family=Montserrat:400,700" rel="stylesheet" type="text/css">
<link href='http://fonts.googleapis.com/css?family=Lobster' rel='stylesheet' type='text/css'>
<link href='http://fonts.googleapis.com/css?family=Raleway:300,400,500,600' rel='stylesheet' type='text/css'>


<!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
<!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
<!--[if lt IE 9]>
    <script src="https://oss.maxcdn.com/libs/respond.js/1.4.2/respond.min.js"></script>
<![endif]-->

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js" ></script>
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>

<script type="text/javascript" src="http://jqueryjs.googlecode.com/files/jquery-1.3.1.min.js" > </script> 

<script type="text/javascript">



    function printDiv(divName) {
        var printContents = document.getElementById(divName).innerHTML;
        console.log(printContents)
        w=window.open();
        w.document.write("<html><head><title>Print Page</title>");
        w.document.write("{% load staticfiles %}")
        w.document.write("<link rel='stylesheet' type='text/css' href='{% static 'home/css/bootstrap.min.css' %}' />")
        w.document.write("<link rel='stylesheet' type='text/css' href='{% static 'home/css/style.css' %}' />")
        w.document.write("<link href='http://fonts.googleapis.com/css?family=Lora:400,700,400italic,700italic' rel='stylesheet' type='text/css'>")
        w.document.write('</head><body>');
        w.document.write(printContents);
        w.document.write('</body></html>');
        w.print();
        w.close();  
    }       


    // Load the Visualization API and the piechart package.        
    google.charts.load('current', {callback: drawChart,packages: ['bar', 'corechart', 'line', 'table'] });

    // Set a callback to run when the Google Visualization API is loaded.
    google.setOnLoadCallback(drawChart);

    function drawChart() {
        var djangoDataTable = {{ tableArr|safe }};
        var dataTable = google.visualization.arrayToDataTable(djangoDataTable);

        var djangoData1 = {{ deathHBV_Final|safe }}
        var data1 = google.visualization.arrayToDataTable(djangoData1);

        var djangoData2 = {{ hcc_Final|safe }}
        var data2 = google.visualization.arrayToDataTable(djangoData2);

        var djangoData3 = {{ cirrhosis_Final|safe }}
        var data3 = google.visualization.arrayToDataTable(djangoData3);



        var options3 = {
            title: "Mortality Rate HBV",
            titleTextStyle :{
                fontSize:26,
                fontName:'Raleway',
            },
            colors: ['#ff7f50','#49B7A8'],

            width: 400,
            height: 400,
            vAxis: {
                title:'Percentage (%)',
                maxValue: 100,
            },
            hAxis:{
                title:'Year',
            },
            legend:{
                position:'none',
                maxLines: 2,
            }
        };

        var options4 = {
            title: "Cirrhosis",
            titleTextStyle :{
                fontSize:26,
                fontName:'Raleway',
            },
            colors: ['#ff7f50','#49B7A8'],
            width: 400,
            height: 400,
            vAxis: {
                title:'Percentage (%)',
                maxValue: 100,
            },
            hAxis:{
                title:'Year',
            },
            legend:{
                position:'none',
                maxLines: 2,
            }
        };

        var options5 = {
            title: "Liver Cancer",
            titleTextStyle :{
                fontSize:26,
                fontName:'Raleway',
            },
            colors: ['#ff7f50','#49B7A8'],

            width: 400,
            height: 400,
            vAxis: {
                title:'Percentage (%)',
                maxValue: 100,
            },
            hAxis:{
                title:'Year',
            },
            legend:{
                position:'none',
                maxLines: 2,
            }
        };

        var optionsTable = {
            'showRowNumber': false,
            'width': '100%',
            'height': '100%',
            'allowHtml': true, 
        };

        var chart3 = new google.visualization.LineChart(document.getElementById('linechart1'));
        chart3.draw(data1, options3);

        if({{ ifCirr }} == 0){
            var chart4 = new google.visualization.LineChart(document.getElementById('linechart2'));
            chart4.draw(data3, options4);
        }

        var chart5 = new google.visualization.LineChart(document.getElementById('linechart3'));
        chart5.draw(data2, options5);

        for (y = 0; y < 4; y++){
            dataTable.setCell(y,0,String(djangoDataTable[y+1][0]),null,{'style': ' font-size:20px;'})
        }

        for (j = 1; j < djangoDataTable[1].length; j += 2){
            for (i = 0; i < 4; i++) { 
                dataTable.setCell(i,j,String(djangoDataTable[i+1][j]),null,{'style': 'background-color: rgba(255,127,80,0.7); font-size:18px;'})
            }
        }

        for (j = 2; j < djangoDataTable[1].length; j += 2){
            for (i = 0; i < 4; i++) { 
                dataTable.setCell(i,j,String(djangoDataTable[i+1][j]),null,{'style': 'background-color: #49b7a8; font-size:18px;'})
            }
        }

        var table = new google.visualization.Table(document.getElementById('table_div'));
        table.draw(dataTable, optionsTable);
    }

    $('#mailform').submit(function(){
        var formAction = $("#selectmail").val() == "technical" ? "research.cs.alc@gmail.com" : "mtoy@stanford.edu";
        $("#mailform").attr("action", "MAILTO:" + formAction);
    }); 

</script>


回答1:


first, it is recommended to use loader.js vs. the older library jsapi.

<script src="https://www.gstatic.com/charts/loader.js"></script>
vs.
<script src="https://www.google.com/jsapi"></script>

next, the load statement should only be called once per page load.
which is probably the reason for random chart selection.
and you can load all the packages you need in one call.

try replacing this...

// Load the Visualization API and the piechart package.
google.load('visualization', '1.0', {'packages':['corechart']});
google.load('visualization', '1', {'packages': ['corechart', 'bar']});
google.load('visualization', '1.1',{'packages': ['line']});
google.load("visualization", "1.0", {'packages':['table']});
// Set a callback to run when the Google Visualization API is loaded.
google.setOnLoadCallback(drawChart);

with this...

google.charts.load('current', {
  callback: drawChart,
  packages: ['bar', 'corechart', 'line', 'table']
});


来源:https://stackoverflow.com/questions/38339239/google-api-visualization-chart-not-working

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!