donjd86266 2015-07-26 03:27
浏览 63
已采纳

在页面上创建多个google.visualization图表

I have a chart that is being generated by using google visualization code see here https://jsfiddle.net/eod8ysm1/

I want to show multiple graphs in a table, in an email so I store all my HTML data in an object ($tempchartData).

 $_SESSION["currentclient"] = $salesmengeotypes[1];
 $_SESSION["noanswer"] = "4";
 $_SESSION["declined"] = "5";
 $_SESSION["other"] = 4;

 ob_start();
 include "piecreator.php";
 $out1 = ob_get_clean();
 $tempchartData .= $out1;

However, it seems to only work with one chart. Is there a way to do this with multiple charts? The file it calls:

<?
$currentclient  =  $_SESSION["currentclient"];
$noanswer  =  $_SESSION["noanswer"];
$declined  =  $_SESSION["declined"];
$other  =  $_SESSION["other"];
?>
<html>
<head>
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript">
    google.load("visualization", "1", {packages:["corechart"]});
    google.setOnLoadCallback(drawChart);
    function drawChart() {
        var data = google.visualization.arrayToDataTable([
            ['Task', 'Hours per Day'],
            ['Signed Up', <? echo $currentclient;?>],
            ['No Answer',  <? echo $noanswer;?>],
            ['Declined',  <? echo $declined;?>],
            ['Other',  <? echo $other;?>]
        ]);

        var options = {
            title: 'Daily Sales Reports'
        };

        var chart = new google.visualization.PieChart(document.getElementById('piechart'));

        chart.draw(data, options);
    }
</script>
</head>
<body>
    <div id="piechart" style="width: 900px; height: 500px;"></div>
</body>
</html>
  • 写回答

1条回答 默认 最新

  • duanmeng3126 2015-07-26 05:15
    关注

    With a bit of modification you can do multiple charts:

    <html>
    <head>
    <script type="text/javascript" src="https://www.google.com/jsapi"></script>
    <script type="text/javascript">
        google.load("visualization", "1", {packages:["corechart"]});
        // Let the callback run a function
        google.setOnLoadCallback(function() {
                // Chart data 1
                SetData1    =   [
                                    ['Task', 'Hours per Day'],
                                    ['Signed Up', 10 ],
                                    ['No Answer',  20],
                                    ['Declined',  40],
                                    ['Other',  30]
                                ];
    
                // Chart data 2
                SetData2    =   [
                                    ['Task', 'Hours per Day'],
                                    ['Signed Up', 5 ],
                                    ['No Answer',  10],
                                    ['Declined',  35],
                                    ['Other',  50]
                                ];
                // Pie Chart 1
                drawChart(SetData1,'piechart');
                // Pie Chart 2
                drawChart(SetData2,'piechart2');
            });
    
        // Give the function some arguments, first is data, second id
        // You could do a third for the options attribute
        function drawChart(ArrayElem,IdElem)
            {
                var data = google.visualization.arrayToDataTable(ArrayElem);
                var options = {
                    title: 'Daily Sales Reports'
                };
    
                var chart = new google.visualization.PieChart(document.getElementById(IdElem));
    
                chart.draw(data, options);
            }
    
    
    </script>
    </head>
    <body>
        <div id="piechart" style="width: 900px; height: 500px;"></div>
        <!-- create a drop for chart 2 -->
        <div id="piechart2" style="width: 900px; height: 500px;"></div>
    </body>
    </html>
    

    jsFiddle DEMO:

    http://jsfiddle.net/vwnsbchh/1/

    For a purely PHP solution (incase you need some dynamics), you can use a class to build the javascript out of php variables. What I have posted works and is offered as is:

    Update: This class (updated to include scatter/trend charts) is available for download (& scrutiny) at https://github.com/rasclatt/PHP-to-Google-PieCharts-Converter

    <?php
        class   GoogleCharts
            {
                public      $newArr;
                public      $VarName;
                public      $DataArray;
    
                protected   $id;
                protected   $compiler;
    
                function CreatePie($settings = false)
                    {
                        if(!is_array($settings))
                            return;
    
                        $data           =   (!empty($settings['data']))? $settings['data']:false;
                        $this->id       =   (!empty($settings['id']))? $settings['id']:false;
                        $incr           =   (!empty($settings['incr']))? $settings['incr']:false;
    
                        $this->VarName  =   "";
                        $this->newArr   =   array();
    
                        if($data != false && $this->id != false) {
                                foreach($data as $key => $value) {
                                        $dvalue         =   (is_numeric($value))? $value:"'{$value}'";
                                        $this->newArr[] =   "\t\t\t\t\t['{$key}', {$dvalue}]";
                                    }
                            }
    
                        $this->VarName  =   "DataSet{$incr}";
    
                        if(!empty($this->newArr)) {
                                $str    =   PHP_EOL."var {$this->VarName}   =   [".PHP_EOL;
                                $str    .=  implode(",".PHP_EOL,$this->newArr).PHP_EOL;
                                $str    .=  "\t\t\t\t]".PHP_EOL;
                            }
    
                        $this->DataArray    =   (!empty($str))? $str:false;
    
                        return $this;
                    }
    
                public  function ChartData()
                    {
                        $str    =   (!empty($this->DataArray))? $this->DataArray:"";
                        $str    .=  PHP_EOL;
    
                        return $str;
                    }
    
                public  function ChartInstance()
                    {
                        $str    =   (!empty($this->VarName))? "drawChart({$this->VarName},'{$this->id}');":"";
                        $str    .=  PHP_EOL;
    
                        return $str;
                    }
    
                public  function CreateJavascript($settings = false)
                    {
                        $library    =   (!empty($settings['lib']))? $settings['lib']:false;
                        $wrap       =   (!empty($settings['wrap']))? $settings['wrap']:false;
                        $wrap       =   (!empty($settings['data']) && is_array($settings['data']))? $settings['data']:array();
    
                        if($library)
                            $comp[] =   '<script type="text/javascript" src="https://www.google.com/jsapi"></script>'.PHP_EOL;
    
                        if($wrap)
                            $comp[] =   '<script type="text/javascript">'.PHP_EOL;
    
                        $comp[] =   '
    google.load("visualization", "1", {packages:["corechart"]});
    // Let the callback run a function
    google.setOnLoadCallback(function() {';
    
                        for($i = 0; $i < count($settings['data']); $i++) {
                                $comp[] =   $settings['data'][$i].PHP_EOL;
                            }
                        $comp[] =   '
        });
    
    // Give the function some arguments, first is data, second id
    // You could do a third for the options attribute
    function drawChart(ArrayElem,IdElem)
        {
            var data = google.visualization.arrayToDataTable(ArrayElem);
            var options = {
                title: \'Daily Sales Reports\'
            };
    
            var chart = new google.visualization.PieChart(document.getElementById(IdElem));
    
            chart.draw(data, options);
        }';
    
                        if($wrap)
                            $comp[] =   '</script>';
    
                        return implode("",$comp);
                    }
            }
    ?>
    

    To use:

    <?php
    // Create instance of GoogleCharts class
    $Googlizer  =   new GoogleCharts();
    ?>
    <html>
    <head>
    <?php
    // Settings for the first chart
    $settings["incr"]               =   1;
    $settings["id"]                 =   "piechart".$settings["incr"];
    $settings["data"]["Task"]       =   "Hours per Day";
    $settings["data"]["Signed Up"]  =   10;
    $settings["data"]["No Answer"]  =   20;
    $settings["data"]["Declined"]   =   40;
    $settings["data"]["Other"]      =   30;
    
    // Create the pie chart
    $Googlizer->CreatePie($settings);
    // Save the instance of the js data array
    $chart1_data    =   $Googlizer->ChartData();
    // Save the instance of the js function
    $chart1_inst    =   $Googlizer->ChartInstance();
    
    // Reset the settings
    $settings                       =   array();
    
    // Create chart 2
    $settings["incr"]               =   2;
    $settings["id"]                 =   "piechart".$settings["incr"];
    $settings["data"]["Task"]       =   "Hours per Day";
    $settings["data"]["Signed Up"]  =   5;
    $settings["data"]["No Answer"]  =   15;
    $settings["data"]["Declined"]   =   25;
    $settings["data"]["Other"]      =   55;
    
    // Same as chart 1
    $Googlizer->CreatePie($settings);
    $chart2_data    =   $Googlizer->ChartData();
    $chart2_inst    =   $Googlizer->ChartInstance();
    
    // Write the whole shebangle to the page
    echo $Googlizer->CreateJavascript(array("data"=>array($chart1_data, $chart1_inst, $chart2_data, $chart2_inst),"wrap"=>true,"lib"=>true));
    ?>
    </head>
    <body>
        <div id="piechart1" style="width: 900px; height: 500px;"></div>
        <!-- create a drop for chart 2 -->
        <div id="piechart2" style="width: 900px; height: 500px;"></div>
    </body>
    </html>
    

    The class will write to page:

    <script type="text/javascript" src="https://www.google.com/jsapi"></script>
    <script type="text/javascript">
    
    google.load("visualization", "1", {packages:["corechart"]});
    // Let the callback run a function
    google.setOnLoadCallback(function() {var DataSet1   =   [
                        ['Task', 'Hours per Day'],
                        ['Signed Up', 10],
                        ['No Answer', 20],
                        ['Declined', 40],
                        ['Other', 30]
                    ]
    
    
    drawChart(DataSet1,'piechart1');
    
    var DataSet2    =   [
                        ['Task', 'Hours per Day'],
                        ['Signed Up', 5],
                        ['No Answer', 15],
                        ['Declined', 25],
                        ['Other', 55]
                    ]
    
    
    drawChart(DataSet2,'piechart2');
    
    
        });
    
    // Give the function some arguments, first is data, second id
    // You could do a third for the options attribute
    function drawChart(ArrayElem,IdElem)
        {
            var data = google.visualization.arrayToDataTable(ArrayElem);
            var options = {
                title: 'Daily Sales Reports'
            };
    
            var chart = new google.visualization.PieChart(document.getElementById(IdElem));
    
            chart.draw(data, options);
        }</script>
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 有偿求码,CNN+LSTM实现单通道脑电信号EEG的睡眠分期评估
  • ¥15 没有证书,nginx怎么反向代理到只能接受https的公网网站
  • ¥50 成都蓉城足球俱乐部小程序抢票
  • ¥15 yolov7训练自己的数据集
  • ¥15 esp8266与51单片机连接问题(标签-单片机|关键词-串口)(相关搜索:51单片机|单片机|测试代码)
  • ¥15 电力市场出清matlab yalmip kkt 双层优化问题
  • ¥30 ros小车路径规划实现不了,如何解决?(操作系统-ubuntu)
  • ¥20 matlab yalmip kkt 双层优化问题
  • ¥15 如何在3D高斯飞溅的渲染的场景中获得一个可控的旋转物体
  • ¥88 实在没有想法,需要个思路