[英]How to chart missing data in chartjs
問題
我想使用 Chartjs 創建一個基於時間的堆積條形圖,但我缺少時間值。 我有兩個問題:
1.) 如何在 SQL 查詢中或在我從 Ajax 響應構建 arrays 時用零填充缺失的數據?
2.)有沒有更好的方法來使用chartjs而不是使用不需要丟失數據的堆疊圖表來可視化數據?
以下是按月總結的簡單說明。 在生產中,這可以動態地更改為每周或每日摘要。 jsFiddle上可用的工作示例
期望的結果:
+----+
|Bill| +----+ +----+
| | |Bill| |Bill|
|----| |----| +----+
|Joe | |Mary| |Mary|
+----+ +----+ +----+
Jan Feb Mar
這是用於說明問題的數據庫表的超簡化版本。
Orders table:
+--------+---------+-------+
|Salesman| Order # | Month |
+--------+---------+-------+
|Bill | 10500 | Jan |
|Bill | 10501 | Jan |
|Joe | 10867 | Jan |
|Mary | 10892 | Feb |
|Bill | 12527 | Feb |
|Mary | 12741 | Mar |
|Bill | 13292 | Mar |
+--------+---------+-------+
SELECT salesman, month, count(*) as orders
FROM orders
GROUP BY month, salesman
ORDER BY month, Salesman
+------+----------+--------+
|Month | Salesman | Orders |
+------+----------+--------+
|Jan | Bill | 2 |
|Jan | Joe | 1 |
|Feb | Mary | 1 |
|Feb | Bill | 1 |
|Mar | Mary | 1 |
|Mar | Bill | 1 |
+------+----------+--------+
Mary 沒有 Jan 的條目,Joe 沒有 Feb 或 Mar 的條目。當我從 ajax 響應構建數組時,x 值的 chart.data.labels 數組是 [Jan, Feb, Mar] 但圖表。 datasets[n].data 的 y 值如下所示:
Bill : [2,1,1]
Joe : [1]
Mary: [1,1]
它們應該如下所示:
Bill : [2,1,1]
Joe : [1,0,0]
Mary: [0,1,1]
@nbk 通過 pivot 表提供了分辨率的線索。 Here's my solution, a PHP function in the controller to dynamically build SQL for a pivot table.
將來可能會將其移至通用實用程序庫。
private function pivotTable($table, $pivotColumn, $pivotLabel, $whereClause, $aggregate="count"){
$returnValue = [];
// validate parms exist
if ((isset($table) != true) ||
(isset($pivotLabel) != true) ||
(isset($pivotColumn) != true)) {
$returnValue['error'] = true;
$returnValue['message'] = 'Invalid parameter';
return $returnValue ;
}
// build the SQL to get the column names and column count
$qry = "SELECT DISTINCT {$pivotColumn} FROM {$table} ";
$where = (isset($whereClause)) ? "WHERE {$whereClause} " : "";
$order = "ORDER BY {$pivotColumn};";
// execute the query
$columns = $this->db->query($qry . $where . $order);
// no columns to pivot
if( $columns->num_rows() < 1) {
$returnValue['error'] = true;
$returnValue['message'] = 'No columns to pivot';
return $returnValue ;
}
// too many columns to pivot
if($columns->num_rows() > 50) {
$returnValue['error'] = true;
$returnValue['message'] = 'Pivot would result in more than 50 columns';
return $returnValue ;
};
// build pivot query
$i = 0;
$pivotQry = "SELECT {$pivotLabel} ";
foreach($columns->result_array() as $column) {
$pivotQry .= ",\r\n{$aggregate}( IF ( {$pivotColumn} = '{$column[$pivotColumn]}', {$pivotColumn}, NULL ) ) as {$column[$pivotColumn]} ";
}
$pivotQry .= "\r\nFROM {$table} \r\n";
$pivotQry .= $where;
$pivotQry .= "GROUP BY {$pivotLabel} ";
$returnValue['error'] = false;
$returnValue['message'] = 'Ok';
$returnValue['sql'] = $pivotQry;
return $returnValue ;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.