如何在一页上添加两个谷歌图表?

Posted

技术标签:

【中文标题】如何在一页上添加两个谷歌图表?【英文标题】:How to add two Google charts on the one page? 【发布时间】:2012-04-10 22:45:00 【问题描述】:

我做了什么

我已将 Google 图表添加到我的页面顶部。这将返回图表的图像。

我需要做什么

我只需要在同一页面上添加第二个图表。

问题

第二个图表的代码被忽略。我主要怀疑这是因为我错误地组合了每个图表的代码。

代码

第一个图表(线):

    <!--Load the AJAX API-->
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript">

  // Load the Visualization API and the piechart package.
  google.load('visualization', '1.0', 'packages':['corechart']);

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

  // Callback that creates and populates a data table,
  // instantiates the pie chart, passes in the data and
  // draws it.
  function drawChart() 

    var data = new google.visualization.DataTable();
    data.addColumn('string', 'Month');
    data.addColumn('number', 'Apples');
    data.addColumn('number', 'Oranges');
    data.addRows([
      ['Oct 11', 20, 0],
      ['Nov 11', 0, 0],
      ['Dec 12',  0, 20],
      ['Jan 12', 0, 10],
      ['Feb 12', 0, 10],
      ['March 12', 10, 10]
    ]);

    // Set chart options
    var options = 'width':960,
                   'height':300;

    // Instantiate and draw our chart, passing in some options.
    var chart = new google.visualization.LineChart(document.getElementById('line_chart'));
    chart.draw(data, options);
  

</script>

第二张图表(饼图):

    <!--Load the AJAX API-->
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript">

  // Load the Visualization API and the piechart package.
  google.load('visualization', '1.0', 'packages':['corechart']);

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

  // Callback that creates and populates a data table,
  // instantiates the pie chart, passes in the data and
  // draws it.
  function drawChart() 

    // Create the data table.
    var data = new google.visualization.DataTable();
    data.addColumn('string', 'Topping');
    data.addColumn('number', 'Slices');
    data.addRows([
      ['Mushrooms', 3],
      ['Onions', 1],
      ['Olives', 1],
      ['Zucchini', 1],
      ['Pepperoni', 2]
    ]);

    // Set chart options
    var options = 'title':'How Much Pizza I Ate Last Night',
                   'width':400,
                   'height':300;

    // Instantiate and draw our chart, passing in some options.
    var chart = new google.visualization.PieChart(document.getElementById('chart_div'));
    chart.draw(data, options);
  
</script>

每个图表都在正文中使用具有唯一 ID 的容器 div 调用:

<div id="chart_div"></div>

我的问题

如何将这两个代码块拼接在一起?我尝试复制 drawChart() 并指定唯一的函数名称和变量,但无济于事。

【问题讨论】:

您应该将您的解决方案作为答案发布,而不是对您的问题进行编辑。回答您自己的问题非常好。 @Kevin Reid - 我重新发布了解决方案作为答案。我只能等待两天才能选择我自己的答案作为接受的答案。感谢您的提示。 我遇到了这个问题,发现这是因为我的 div 元素写成 而不是显式的开始/结束元素 。如果其他人在渲染多个图表时遇到问题,请检查。 The Best Easy Solution 【参考方案1】:

解决方案

我现在有一个可行的解决方案。它涉及辨别示例代码的哪些部分要复制,哪些部分不应该复制(正如 Oofpez 所建议的那样)。每个图表的数据、选项和图表变量都在 ONE drawChart() 函数中定义。

这是一个工作示例(只需复制并粘贴到 html 文档中):

...此示例进一步演示了如何组合不同的图表类型,即饼图和折线图...

<html>
      <head>
        <!--Load the AJAX API-->
        <script type="text/javascript" src="https://www.google.com/jsapi"></script>
        <script type="text/javascript">

          // Load the Visualization API and the piechart package.
          google.load('visualization', '1.0', 'packages':['corechart']);

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

          // Callback that creates and populates a data table,
          // instantiates the pie chart, passes in the data and
          // draws it.
          function drawChart() 

            // Create the data table.
            var data = new google.visualization.DataTable();
            data.addColumn('string', 'Topping');    
            data.addColumn('number', 'Slices');
            data.addRows([
              ['Mushrooms', 3],
              ['Onions', 1],
              ['Olives', 1],
              ['Zucchini', 1],
              ['Pepperoni', 2]
            ]);
            // Create the data table.
            var data2 = new google.visualization.DataTable();
            data2.addColumn('string', 'Topping');
            data2.addColumn('number', 'Slices');
            data2.addRows([
              ['Mushrooms', 3],
              ['Onions', 1],
              ['Olives', 15],
              ['Zucchini', 1],
              ['Pepperoni', 2]
            ]);

            var data3 = new google.visualization.DataTable();
            data3.addColumn('string', 'Year');
            data3.addColumn('number', 'Sales');
            data3.addColumn('number', 'Expenses');
            data3.addRows([
              ['2004', 1000, 400],
              ['2005', 1170, 460],
              ['2006',  860, 580],
              ['2007', 1030, 540]
            ]);

            // Set chart options
            var options = 'title':'How Much Pizza I Ate Last Night',
                           'width':400,
                           'height':300;
            // Set chart options
            var options2 = 'title':'How Much Pizza You Ate Last Night',
                           'width':400,
                           'height':300;
            // Set chart options
            var options3 = 'title':'Line chart',
                           'width':400,
                           'height':300;

            // Instantiate and draw our chart, passing in some options.
            var chart = new google.visualization.PieChart(document.getElementById('chart_div'));
            chart.draw(data, options);
            var chart2 = new google.visualization.PieChart(document.getElementById('chart_div2'));
            chart2.draw(data2, options2);
            var chart3 = new google.visualization.LineChart(document.getElementById('chart_div3'));
            chart3.draw(data3, options3);

          
        </script>
      </head>

      <body>
        <!--Divs that will hold the charts-->
        <div id="chart_div"></div>
        <div id="chart_div2"></div>
        <div id="chart_div3"></div>
      </body>
    </html>

【讨论】:

这仅在您知道在任何给定时间将拥有多少张图表时才有效。 @avoliva 请看***.com/questions/34662223/…【参考方案2】:

基本上你可以包装函数drawChart 来传递参数:

function drawChart(chartType, containerID, dataArray, options)

call google.setOnLoadCallback(function() 
    drawChart('barChart', 'div_id_1', test_array, null);
); 

你想渲染图形的次数:

var test_array = [
    ['Name', 'Count-A', 'Count-B'],
    ['Test-A', 4, 3],
    ['Test-B', 1, 2],
    ['Test-C', 3, 4],
    ['Test-D', 2, 0],
    ['Test-E', 2, 5]
];

google.load("visualization", "1", packages: ["corechart",'table']);

google.setOnLoadCallback(function() 
    drawChart('barChart', 'div_id_1', test_array, null);
);

google.setOnLoadCallback(function() 
    drawChart('columnChart', 'div_id_2', test_array, null);
);


function drawChart(chartType, containerID, dataArray, options) 
    var data = google.visualization.arrayToDataTable(dataArray);
    var containerDiv = document.getElementById(containerID);
    var chart = false;

    if (chartType.toUpperCase() == 'BARCHART') 
        chart = new google.visualization.BarChart(containerDiv);
    
    else if (chartType.toUpperCase() == 'COLUMNCHART') 
        chart = new google.visualization.ColumnChart(containerDiv);
    
    else if (chartType.toUpperCase() == 'PIECHART') 
        chart = new google.visualization.PieChart(containerDiv);
    
    else if (chartType.toUpperCase() == 'TABLECHART')
    
        chart = new google.visualization.Table(containerDiv);
    

    if (chart == false) 
        return false;
    

    chart.draw(data, options);

【讨论】:

这是我选择的路线,但发现它不适用于新的材料线图。适用于经典。使用材料,每次刷新时显示的图表都不同:) 一个 JSfiddle 的例子会有很长的路要走。【参考方案3】:

基于@Dominor 的回答,但是如果您要从任意位置注册图表,只需构建一个在回调函数中执行的函数堆栈,如下所示:

google.setOnLoadCallback(drawChart);

// Callback that creates and populates a data table,
// instantiates the pie chart, passes in the data and
// draws it.
googleChartStack = [];

function drawChart() 
    for (var i = googleChartStack.length - 1; i >= 0; i--) 
        googleChartStack[i]();
    

然后,您可以在模板中的其他位置推送到此堆栈。在我的示例中,我正在遍历一些模板 sn-p。

<script>
  googleChartStack.push(function() 
    var data = google.visualization.arrayToDataTable([
      ['A', 'B'],
      ['A', 1],
      ['B', 2]
    ]);

    var options = 
      title: 'none',
      legend: 'none'
    ;

    var chart = new google.visualization.PieChart(document.getElementById("relevant-id"));
    chart.draw(data, options);          
  )
</script>

【讨论】:

这与我最终做的很接近。我来这里是为了发布我的作品,但我会支持你的作品,因为它体现了同样的精神。构建一堆谷歌图表,然后一次性加载它们。【参考方案4】:

Google Charts 的生产版本存在一个计时错误,该错误会阻止在同一页面上加载多个图表。

Google 在最近的版本中修复了此问题,可用于冻结版本加载器:https://developers.google.com/chart/interactive/docs/library_loading_enhancements#frozen-versions

相关话题:https://groups.google.com/forum/?utm_medium=email&utm_source=footer#!msg/google-visualization-api/KulpuT418cg/yZieM8buCQAJ

【讨论】:

我知道这是一个谷歌错误。这为我节省了几个小时。【参考方案5】:

也许当你指定时

google.setOnLoadCallback(drawChart);

第一次覆盖回调事件两次?

只是猜测...

【讨论】:

谢谢。它是。我想出了如何避免必须使用该功能两次。有关解决方案的完整说明,请参阅我的原始帖子。【参考方案6】:

在上面的答案包中只添加了饼图..为了在同一页面上打印饼图和折线图,我们还必须包括线包: google.load('visualization', '1.0', 'packages':['corechart','line']);

完整代码:-

      // Load the Visualization API and the piechart package.
      google.load('visualization', '1.0', 'packages':['corechart','line']);

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

      // Callback that creates and populates a data table,
      // instantiates the pie chart, passes in the data and
      // draws it.
      function drawChart() 

        // Create the data table.
        var data = new google.visualization.DataTable();
        data.addColumn('string', 'Topping');    
        data.addColumn('number', 'Slices');
        data.addRows([
          ['Mushrooms', 3],
          ['Onions', 1],
          ['Olives', 1],
          ['Zucchini', 1],
          ['Pepperoni', 2]
        ]);
        // Create the data table.
        var data2 = new google.visualization.DataTable();
        data2.addColumn('string', 'Topping');
        data2.addColumn('number', 'Slices');
        data2.addRows([
          ['Mushrooms', 3],
          ['Onions', 1],
          ['Olives', 15],
          ['Zucchini', 1],
          ['Pepperoni', 2]
        ]);

        var data3 = new google.visualization.DataTable();
        data3.addColumn('string', 'Year');
        data3.addColumn('number', 'Sales');
        data3.addColumn('number', 'Expenses');
        data3.addRows([
          ['2004', 1000, 400],
          ['2005', 1170, 460],
          ['2006',  860, 580],
          ['2007', 1030, 540]
        ]);

        // Set chart options
        var options = 'title':'How Much Pizza I Ate Last Night',
                       'width':400,
                       'height':300;
        // Set chart options
        var options2 = 'title':'How Much Pizza You Ate Last Night',
                       'width':400,
                       'height':300;
        // Set chart options
        var options3 = 'title':'Line chart',
                       'width':400,
                       'height':300;

        // Instantiate and draw our chart, passing in some options.
        var chart = new google.visualization.PieChart(document.getElementById('chart_div'));
        chart.draw(data, options);
        var chart2 = new google.visualization.PieChart(document.getElementById('chart_div2'));
        chart2.draw(data2, options2);
        var chart3 = new google.visualization.LineChart(document.getElementById('chart_div3'));
        chart3.draw(data3, options3);

      
    </script>
  </head>

  <body>
    <!--Divs that will hold the charts-->
    <div id="chart_div"></div>
    <div id="chart_div2"></div>
    <div id="chart_div3"></div>
  </body>
</html>

【讨论】:

【参考方案7】:

您要做的是为每个图表设置一个函数。然后做

google.setOnLoadCallback(initialize);

并初始化调用每个函数来创建图表。这样比在一个函数中绘制多个图表要干净得多。它也将有助于调试。

【讨论】:

【参考方案8】:
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript">
  google.load("visualization", "1.1", packages:["bar"]);
  google.setOnLoadCallback(drawChart);
  function drawChart() 
    var data = google.visualization.arrayToDataTable([
      ['Day/Month', 'Sales', 'Goal'],
      ['Daily', 33549.17,47328.04],
      ['M-T-D', 96114.18,141984.12]
    ]);


    var data1 = google.visualization.arrayToDataTable([
      ['Day/Month', 'Bookings', 'Goal'],

      ['Daily', 37991.21,47659.09],

      ['M-T-D', 95610.47,142977.27]

    ]);
   var options = 
  colors: ['#e0aa0e', '#ecbb6e','green'],
      width: 800,
      chart: 
        title: 'Test Company Sales',
        subtitle: 'Sales vs Goal',
      
    ;
    var options1 = 
  colors: ['#e0440e', '#ec8f6e','green'],
      width: 800,
      chart: 
        title: 'Test Company Bookings',
        subtitle: 'Bookings',
      
    ;

    var chart = new google.charts.Bar(document.getElementById('sales'));
    chart.draw(data, options);
    var chart2 = new google.charts.Bar(document.getElementById('bookings'));

    chart2.draw(data1, options1);
  
</script>





  <div style="display: table; width: 100%;">
      <div style="display: table-row">
           <div id="sales" style="width: 900px; height: 500px; display: table-cell;"></div>
          <div id="bookings" style="width: 900px; height: 500px; display: table-cell;"></div>
     </div>
</div>

【讨论】:

我无法用上面的代码同时渲染两个图。【参考方案9】:

step_1.(将 id curve_chart 更改为其他名称(例如 ajay))

<body>
<div id="ajay" style="width: 900px; height: 500px"></div>

step_2.(在脚本元素中将此 id 分配给您的图表)..

    var chart = new google.visualization.LineChart(document.getElementById('ajay'));

    chart.draw(data, options);
  
</script>

【讨论】:

以上是关于如何在一页上添加两个谷歌图表?的主要内容,如果未能解决你的问题,请参考以下文章

Plotly:如何使用plotly-dash在一页上创建“输入文本”并在第二页或选项卡上输出(图形)?

如何在一页上使用多个 AdSense 单元?

如何在一页上切换多个 tabSlideOUT 选项卡

如何在一页上运行多个版本的 Zepto.js? [关闭]

如何使我的图像停留在一页上而不重复?

Mailchimp 在一页上嵌入两个表单