Created
August 25, 2022 14:33
-
-
Save alistaircol/ae99d0cf4d57617c283b132aec9bfc48 to your computer and use it in GitHub Desktop.
Chartjs Horizontal Bar Chart DTO - see https://ac93.uk/articles/laravel-chartjs-blade-browsershot/ for context
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
namespace App\Charts; | |
use Spatie\DataTransferObject\DataTransferObject; | |
use Illuminate\Support\Collection; | |
class HorizontalBarChart extends DataTransferObject | |
{ | |
public const MEASUREMENT_RELATIVE = 'relative'; | |
public const MEASUREMENT_ABSOLUTE = 'absolute'; | |
public const CHART_COLOR_BAR_RELATIVE = '#E46C0A'; | |
public const CHART_COLOR_BAR_ABSOLUTE = '#8FB4E3'; | |
public string $color; | |
public array $labels; | |
public array $data; | |
public static function make(Collection $data, string $measurement): self | |
{ | |
return new self([ | |
'color' => $measurement === self::MEASUREMENT_RELATIVE | |
? self::CHART_COLOR_BAR_RELATIVE | |
: self::CHART_COLOR_BAR_ABSOLUTE, | |
'labels' => $dataset->map(fn (ChartItemDto $item) => $item->name)->toArray(), | |
'data' => $measurement === self::MEASUREMENT_RELATIVE | |
? $dataset->map(fn (ChartItemDto $item) => $item->relative)->toArray() | |
: $dataset->map(fn (ChartItemDto $item) => $item->absolute)->toArray(), | |
]); | |
} | |
public function toArray(): array | |
{ | |
return [ | |
'type' => 'bar', | |
'data' => [ | |
'labels' => $this->labels, | |
'datasets' => [ | |
[ | |
'data' => $this->data, | |
'backgroundColor' => $this->color, | |
], | |
], | |
], | |
'options' => [ | |
'animation' => false, | |
'indexAxis' => 'y', | |
'scales' => [ | |
'y' => [ | |
'ticks' => [ | |
// Setting `autoSkip` to false means that it will not collapse labels, | |
// which happens by default and is undesirable in my case since each item's | |
// label is required to be visible. | |
'autoSkip' => false, | |
// Adding some padding to add some space between the label and the chart. | |
'padding' => 12, | |
], | |
'grid' => [ | |
// Disable the horizontal grid lines. | |
'display' => false, | |
], | |
], | |
'x' => [ | |
'ticks' => [ | |
// I want to add some space between the bottom of | |
// the graph, and the item's value. | |
'padding' => 12, | |
], | |
'grid' => [ | |
// I do not want to draw tick lines below the bottom of the graph. | |
'tickLength' => 0, | |
], | |
], | |
], | |
'plugins' => [ | |
'legend' => [ | |
'display' => false, | |
], | |
], | |
], | |
]; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment