Skip to content

Commit

Permalink
Support for stacked bar chart, adding additional colour for longer da…
Browse files Browse the repository at this point in the history
…tasets
  • Loading branch information
mvorisek committed Aug 20, 2022
1 parent 0108b89 commit 837c0c5
Showing 1 changed file with 16 additions and 1 deletion.
17 changes: 16 additions & 1 deletion src/Chart.php
Original file line number Diff line number Diff line change
Expand Up @@ -28,11 +28,15 @@ class Chart extends View
['rgba(75, 192, 192, 0.2)', 'rgba(75, 192, 192, 1)'],
['rgba(153, 102, 255, 0.2)', 'rgba(153, 102, 255, 1)'],
['rgba(255, 159, 64, 0.2)', 'rgba(255, 159, 64, 1)'],
['rgba(20, 20, 20, 0.2)', 'rgba(20, 20, 20, 1)'],
];

/** @var array Options for chart.js widget */
public $options = [];

/** @var array Set stack id for each column, leave empty if no stacks */
public $stacks = [];

/** @var array Labels for axis. Fills with setModel(). */
protected $labels;

Expand Down Expand Up @@ -100,14 +104,19 @@ public function setOptions(array $options)
*
* This component will automatically figure out name of the chart,
* series titles based on column captions etc.
*
* Example for bar chart with two side-by side bars per category, and one of them stacked:
*
* $chart->setModel($model, ['month', 'turnover_month_shoes', 'turnover_month_shirts', 'turnover_month_trousers', 'turnover_month_total_last_year'], [0,0,0,1]);
*/
public function setModel(Model $model, array $columns = []): void
public function setModel(Model $model, array $columns = [], array $stacks = []): void
{
if (!$columns) {
throw new Exception('Second argument must be specified to Chart::setModel()');
}

$this->datasets = [];
$this->stacks = $stacks;

// initialize data-sets
foreach ($columns as $key => $column) {
Expand All @@ -118,16 +127,22 @@ public function setModel(Model $model, array $columns = []): void
}

$colors = array_shift($this->niceColors);
$stack = array_shift($this->stacks);

$this->datasets[$column] = [
'label' => $model->getField($column)->getCaption(),
'backgroundColor' => $colors[0],
'borderColor' => $colors[1],
'borderWidth' => 1,
'stack' => $stack,
'data' => [],
];
}

if ($stacks !== []) {
$this->setOptions(['scales' => ['yAxes' => [0 => ['stacked' => true]], 'xAxes' => [0 => ['stacked' => true]]]]);
}

// prepopulate data-sets
foreach ($model as $entity) {
$this->labels[] = $entity->get($titleColumn); // @phpstan-ignore-line
Expand Down

0 comments on commit 837c0c5

Please sign in to comment.