最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Change Google Chart bar colors when data table input is from JSON data from server - Stack Overflow

programmeradmin6浏览0评论

I have been struggling with google chart API. And I found this brilliant example on SO PHP MySQL Google Chart JSON - Complete Example .

However I was wondering how could I change the bar color from the dafault blue color. I am confused on how should I use the { role: 'style' } function.

Here is my code :

     <?php
    $con=mysql_connect("localhost","username","pass") or die("Failed to connect with database");
    mysql_select_db("rosac", $con); 
    $query = mysql_query("
    SELECT TarikhLulusTahun AS Tahun, COUNT(*) AS Jumlah 
FROM association 
GROUP BY TarikhLulusTahun");


    $rows = array();
    $table = array();
    $table['cols'] = array(

        array('label' => 'Tahun', 'type' => 'string'),
        array('label' => 'Jumlah Persatuan', 'type' => 'number')
        ({type: 'string', role: 'style'})

    );

    $rows = array();
    while($r = mysql_fetch_assoc($query)) {
        $temp = array();
        $temp[] = array('v' => (string) $r['Tahun']); 

        $temp[] = array('v' => (int) $r['Jumlah']); 
        $rows[] = array('c' => $temp);
    }

    $table['rows'] = $rows;
    $jsonTable = json_encode($table);
    //echo $jsonTable;
    ?>

    <html>
      <head>
        <!--Load the Ajax API-->
        <script type="text/javascript" src=""></script>
        <script type="text/javascript" src=".8.2/jquery.min.js"></script>
        <script type="text/javascript">

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

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

        function drawChart() {

          // Create our data table out of JSON data loaded from server.
          var data = new google.visualization.DataTable(<?=$jsonTable?>);
          var options = {
               title: 'Jumlah Persatuan Berdaftar Mengikut Tahun',
              is3D: 'true',
              width: 1000,
              height: 1000,
             hAxis: {title: 'Tahun', titleTextStyle: {color: 'red'}},
             vAxis: {title: 'Jumlah Persatuan', titleTextStyle: {color: 'blue'}}
            };

          var chart = new google.visualization.ColumnChart(document.getElementById('chart_div'));
          chart.draw(data, options);
        }
        </script>
      </head>

      <body>
        <!--this is the div that will hold the pie chart-->
        <div id="chart_div"></div>
      </body>
    </html>

I have been struggling with google chart API. And I found this brilliant example on SO PHP MySQL Google Chart JSON - Complete Example .

However I was wondering how could I change the bar color from the dafault blue color. I am confused on how should I use the { role: 'style' } function.

Here is my code :

     <?php
    $con=mysql_connect("localhost","username","pass") or die("Failed to connect with database");
    mysql_select_db("rosac", $con); 
    $query = mysql_query("
    SELECT TarikhLulusTahun AS Tahun, COUNT(*) AS Jumlah 
FROM association 
GROUP BY TarikhLulusTahun");


    $rows = array();
    $table = array();
    $table['cols'] = array(

        array('label' => 'Tahun', 'type' => 'string'),
        array('label' => 'Jumlah Persatuan', 'type' => 'number')
        ({type: 'string', role: 'style'})

    );

    $rows = array();
    while($r = mysql_fetch_assoc($query)) {
        $temp = array();
        $temp[] = array('v' => (string) $r['Tahun']); 

        $temp[] = array('v' => (int) $r['Jumlah']); 
        $rows[] = array('c' => $temp);
    }

    $table['rows'] = $rows;
    $jsonTable = json_encode($table);
    //echo $jsonTable;
    ?>

    <html>
      <head>
        <!--Load the Ajax API-->
        <script type="text/javascript" src="https://www.google./jsapi"></script>
        <script type="text/javascript" src="http://ajax.googleapis./ajax/libs/jquery/1.8.2/jquery.min.js"></script>
        <script type="text/javascript">

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

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

        function drawChart() {

          // Create our data table out of JSON data loaded from server.
          var data = new google.visualization.DataTable(<?=$jsonTable?>);
          var options = {
               title: 'Jumlah Persatuan Berdaftar Mengikut Tahun',
              is3D: 'true',
              width: 1000,
              height: 1000,
             hAxis: {title: 'Tahun', titleTextStyle: {color: 'red'}},
             vAxis: {title: 'Jumlah Persatuan', titleTextStyle: {color: 'blue'}}
            };

          var chart = new google.visualization.ColumnChart(document.getElementById('chart_div'));
          chart.draw(data, options);
        }
        </script>
      </head>

      <body>
        <!--this is the div that will hold the pie chart-->
        <div id="chart_div"></div>
      </body>
    </html>
Share Improve this question edited May 23, 2017 at 12:00 CommunityBot 11 silver badge asked Jan 14, 2014 at 16:26 mfmzmfmz 2271 gold badge5 silver badges19 bronze badges 0
Add a ment  | 

3 Answers 3

Reset to default 7

You need to do a couple of things. First, your column creation is wrong; this:

$table['cols'] = array(
    array('label' => 'Tahun', 'type' => 'string'),
    array('label' => 'Jumlah Persatuan', 'type' => 'number')
    ({type: 'string', role: 'style'})
);

should be like this:

$table['cols'] = array(
    array('label' => 'Tahun', 'type' => 'string'),
    array('label' => 'Jumlah Persatuan', 'type' => 'number'),
    array('type' => 'string', 'p' => array('role' => 'style'))
);

Then, when you are creating the rows of data, you need to add a cell for the style:

while($r = mysql_fetch_assoc($query)) {
    $temp = array();
    $temp[] = array('v' => (string) $r['Tahun']); 
    $temp[] = array('v' => (int) $r['Jumlah']); 
    $temp[] = array('v' => <insert style here>); 
    $rows[] = array('c' => $temp);
}
    $table = array();
    $table['cols'] = array(
        array('id' => "", 'label' => 'Category', 'pattern' => "", 'type' => 'string'),
        array('id' => "", 'label' => 'Budgeted', 'pattern' => "", 'type' => 'number'),
        array('type' => 'string', 'p' => array('role' => 'style'))
    );

    $rows = array();
    while($r = mysql_fetch_assoc($result_chart)) {

        $temp = array();
        $temp[] = array('v' => (string) $r['Groups']); 
        $temp[] = array('v' => (int) $r['Amount']); 
        $temp[] = array('v' => 'color: #0000cf; stroke-color: #cf001d');
            $rows[] = array('c' => $temp);
    }

    $table['rows'] = $rows;
    $jsonTable = json_encode($table);

Close PHP section, then

    <script type="text/javascript" src="https://www.google./jsapi"></script>
    <script type="text/javascript">

    google.load('visualization', '1', {'packages':['corechart']});

    google.setOnLoadCallback(drawChart);

    function drawChart() {
        var data = new google.visualization.DataTable(<?php echo $jsonTable; ?>);

        var options = {
        width: 980,
        height: 500,
        backgroundColor: '#F6F6F6'
        };

        var chart = new google.visualization.ColumnChart(document.getElementById('chart_div'));

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

PRIVACY BY DESIGN

Both other answers are useful (UPVOTED both). Nevertheless, I'll toss my hat in the ring for illustrative purposes. Below I simulate a somewhat safer application, using client side AJAX to consume data from restful JSON on a server. This has the advantage of not exposing database structure or credentials (supposing that the RESTful server is separate from the one the final page runs on).

I show 2 alternatives (slightly different declarations), which both work for simple bar color (color and color2). In your final code, use whichever one suits you best.

Serverside RESTful php

$graphData = array(
    'colors' => array(
    'cols' => array(
        array('type' => 'string', 'label' => 'Tahun'),
        array('type' => 'number', 'label' => 'Jumlah'),
        array('type' => 'string', 'p' => array('role' => 'style'))
    ),  
    'rows' => array()
    ),
    'colors2' => array(
    'cols' => array(
        array('type' => 'string', 'label' => 'Tahun'),
        array('type' => 'number', 'label' => 'Jumlah'),
        array('type' => 'string', 'role' => 'style')
    ),
    'rows' => array()
    )
);
[...]
$sql="SELECT  `Tahun`, `Jumlah`, `Color` FROM [...] ";
$result = mysqli_query($conn, $sql) or trigger_error(mysqli_error($conn));
while($row = mysqli_fetch_array($result)){
    $graphData['colors']['rows'][] = array('c' => array(
        array('v' => $row['Tahun']),
        array('v' => (int)$row['Jumlah']),
        array('v' => $row['Color'])
    ));
    $graphData['colors2']['rows'][] = array('c' => array(
        array('v' => $row['Tahun']),
        array('v' => (int)$row['Jumlah']),
        array('v' => $row['Color'])
    ));
}
// $row['Color'] is formatted as "color: #FF0000"
echo json_encode($graphData);

Client side browser JavaScript

var jsonDataAjax = $.ajax({
    url: "http://yourdomain./yourRestfulJson.php",
    dataType: "json",
    async: false
    }).responseText;
var jsonData = eval("(" + jsonDataAjax + ")");

var jsonColors = new google.visualization.DataTable(jsonData.colors);
var jsonColors2 = new google.visualization.DataTable(jsonData.colors2);

var viewColors = new google.visualization.DataView(jsonColors);
viewColors.setColumns([0, 1,
           { calc: "stringify",
             sourceColumn: 1,
             type: "string",
             role: "annotation" },
           2]);   
                    
var viewColors2 = new google.visualization.DataView(jsonColors2);
viewColors2.setColumns([0, 1,
           { calc: "stringify",
             sourceColumn: 1,
             type: "string",
             role: "annotation" },
           2, {type: 'string', role: 'style'}]);        

var options = {
    title: "ColumnChart Color Testing Graph",
    width: 1200,
    height: 400,
    bar: {groupWidth: "95%"},
    legend: { position: "none" },
};

var chart1 = new google.visualization.ColumnChart(document.getElementById('bar1_div'));
var chart2 = new google.visualization.ColumnChart(document.getElementById('bar2_div'));

chart1.draw(viewColors, options);
chart2.draw(viewColors2, options);
发布评论

评论列表(0)

  1. 暂无评论
ok 不同模板 switch ($forum['model']) { /*case '0': include _include(APP_PATH . 'view/htm/read.htm'); break;*/ default: include _include(theme_load('read', $fid)); break; } } break; case '10': // 主题外链 / thread external link http_location(htmlspecialchars_decode(trim($thread['description']))); break; case '11': // 单页 / single page $attachlist = array(); $imagelist = array(); $thread['filelist'] = array(); $threadlist = NULL; $thread['files'] > 0 and list($attachlist, $imagelist, $thread['filelist']) = well_attach_find_by_tid($tid); $data = data_read_cache($tid); empty($data) and message(-1, lang('data_malformation')); $tidlist = $forum['threads'] ? page_find_by_fid($fid, $page, $pagesize) : NULL; if ($tidlist) { $tidarr = arrlist_values($tidlist, 'tid'); $threadlist = well_thread_find($tidarr, $pagesize); // 按之前tidlist排序 $threadlist = array2_sort_key($threadlist, $tidlist, 'tid'); } $allowpost = forum_access_user($fid, $gid, 'allowpost'); $allowupdate = forum_access_mod($fid, $gid, 'allowupdate'); $allowdelete = forum_access_mod($fid, $gid, 'allowdelete'); $access = array('allowpost' => $allowpost, 'allowupdate' => $allowupdate, 'allowdelete' => $allowdelete); $header['title'] = $thread['subject']; $header['mobile_link'] = $thread['url']; $header['keywords'] = $thread['keyword'] ? $thread['keyword'] : $thread['subject']; $header['description'] = $thread['description'] ? $thread['description'] : $thread['brief']; $_SESSION['fid'] = $fid; if ($ajax) { empty($conf['api_on']) and message(0, lang('closed')); $apilist['header'] = $header; $apilist['extra'] = $extra; $apilist['access'] = $access; $apilist['thread'] = well_thread_safe_info($thread); $apilist['thread_data'] = $data; $apilist['forum'] = $forum; $apilist['imagelist'] = $imagelist; $apilist['filelist'] = $thread['filelist']; $apilist['threadlist'] = $threadlist; message(0, $apilist); } else { include _include(theme_load('single_page', $fid)); } break; default: message(-1, lang('data_malformation')); break; } ?>