【问题标题】:How to draw a google line chart using the below code?如何使用以下代码绘制谷歌折线图?
【发布时间】:2013-07-14 06:00:42
【问题描述】:

我想使用“Google Charts”工具绘制折线图。我正在从 MySql 数据库中获取折线图所需的数据。它的代码如下:

    <?php
    require_once('../includes/public-application-header.php');
    $con=mysql_connect("localhost","root","eywaadmin") or die("Failed to connect with database!!!!");
  mysql_select_db("OCN", $con); 

    $sql  =" SELECT DATE_FORMAT( FROM_UNIXTIME( transaction_date ) , '%d/%m/%Y') 'transaction_date', COUNT(*) 'total count', SUM(transaction_status = 'success') ";
    $sql .=" success, SUM(transaction_status = 'inprocess') inprocess, SUM(transaction_status = 'fail') fail, ";
    $sql .=" SUM(transaction_status = 'cancelled') cancelled FROM user_transaction WHERE ";
    $sql .=" transaction_date >= 1325376000 AND transaction_date <= 1373846400 GROUP BY date(FROM_UNIXTIME(transaction_date)) ";

    $r= mysql_query($sql) or die(mysql_error()); 
    $transactions = array();
    while($result  = mysql_fetch_array($r, MYSQL_ASSOC)){
      $transactions[] = $result;
    } 
    $rows = array();
      //flag is not needed
      $flag = true;
      $table = array();
      $table['cols'] = array(

    // Labels for your chart, these represent the column titles
    // Note that one column is in "string" format and another one is in "number" format as pie chart only required "numbers" for calculating percentage and string will be used for column title
    array('label' => 'Transaction Date', 'type' => 'string'),
    array('label' => 'Total Count', 'type' => 'number'),
    array('label' => 'Success', 'type' => 'number'),
    array('label' => 'Inprocess', 'type' => 'number'),
    array('label' => 'Failed', 'type' => 'number'),
    array('label' => 'Cancelled', 'type' => 'number'),
    );
  $rows = array();

  foreach($transactions as $tr) {
    $temp = array();

     foreach($tr as $key=>$value){

    // the following line will be used to slice the Pie chart
    $temp[] = array('v' => (string) $key); 

    // Values of each slice
    $temp[] = array('v' => (int) $value);     
    }
  $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.com/jsapi"></script>
    <script type="text/javascript" src="http://ajax.googleapis.com/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: 'User Transaction Statistics',
          is3D: 'true',
          width: 800,
          height: 600
        };
      // Instantiate and draw our chart, passing in some options.
      // Do not forget to check your div ID
      var chart = new google.visualization.LineChart(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>

我想将日期(即事务日期)放在 X 轴上,将计数值(即 10、20、30、40)放在 Y 轴上。但不幸的是,我没有得到所需格式的折线图。我附上执行上述代码后得到的屏幕截图。

有人可以在这方面帮助我吗?提前致谢。如果您想了解更多信息,我可以将其添加到问题正文中。 根据jmac 的请求,我发布了为您参考而创建的 json 响应。如果您仍然需要查询输出等任何其他内容,我可以为您提供。附上折线图的屏幕截图。

【问题讨论】:

  • 如果您向我们提供您正在绘制的data 对象的转储,这将有所帮助,这样我们就可以看到实际绘制的内容,因为我们都无法访问您的数据库,这就是问题来自。

标签: php mysql associative-array google-visualization


【解决方案1】:

您输入的数据不正确。试试这个:

foreach ($transactions as $tr) {
    $temp = array();

    $temp[] = array('v' => $tr['transaction_date']);
    $temp[] = array('v' => (int) $tr['total count']);
    $temp[] = array('v' => (int) $tr['success']);
    $temp[] = array('v' => (int) $tr['inprocess']);
    $temp[] = array('v' => (int) $tr['fail']);
    $temp[] = array('v' => (int) $tr['cancelled']);

    $rows[] = array('c' => $temp); 
}

这将生成一个带有离散轴的图表,其中每行数据在图表上均匀分布,无论日期之间的距离如何。如果您想要一个连续轴(请参阅 this 作为离散和连续之间差异的示例),您必须稍微不同地格式化您的日期:

在列中:

array('label' => 'Transaction Date', 'type' => 'date')

在行中:

$dateArray = explode('/', $tr['transaction_date']);
$year = $dateArray[2];
$month = $dateArray[1] - 1; // need to subtract 1 to convert to javascript month format
$day = $dateArray[0];
$temp[] = array('v' => "Date($year, $month, $day)", f: $tr['transaction_date']);

然后您可以在图表的选项中格式化日期轴:

hAxis: {
    format: 'd/M/yyyy'
}

顺便说一句,您可以去掉 PHP 中的 $flag 变量——它是我很久以前在 Google 可视化 API 组中作为示例发布的原始代码遗留下来的工件。每当该代码被复制时,它就会不断出现,并且没有人将其删除。

【讨论】:

    【解决方案2】:

    我不知道你的 jsonTable 长什么样,但应该这样格式化:

    ['transaction date', 'Total count', 'Succes', 'In progress', 'Failed', 'Canceled'],
    ['19-7-2013', 50, 40, 5, 2, 3],
    ['20-7-2013', 60, 50, 5, 1, 4],
    ['21-7-2013', 50, 40, 5, 2, 3],
    ['22-7-2013', 60, 50, 5, 1, 4],
    ['23-7-2013', 50, 40, 5, 2, 3]
    

    你能把你的 $jsonTable 发给我吗?

    此链接向您展示了该表的示例:http://jsfiddle.net/kxd2u/

    我认为您对数据量没有问题。我自己用大量数据制作了一些图表,一切正常!

    【讨论】:

      【解决方案3】:

      主要问题是您要保存数据集中的列名和列值。您应该只存储值。

      $temp = array();
      foreach($tr as $key=>$value){
        // Values of each slice
        $temp[] = array('v' => (int) $value);     
      }
      $rows[] = array('c' => $temp);                         
      

      第二个问题是将所有值转换为整数。如果您希望日期显示为实际日期,则应取消该转换。

      $temp = array();
      foreach($tr as $key=>$value){
        // Values of each slice
        $temp[] = array('v' => $value);     
      }
      $rows[] = array('c' => $temp);                         
      

      【讨论】:

        猜你喜欢
        • 2010-10-14
        • 1970-01-01
        • 1970-01-01
        • 2016-05-14
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-07-02
        相关资源
        最近更新 更多