Range grouping data and label in Chartjs - php

So, I would like to range my data and labels in Chartjs so that I can represent them properly.
Please take a look at this reference which exactly shows what I am trying to do.
You can see that the data is grouped and ranged according to the order totals. The bar is then representing the total order counts.
One thing to notice here is that this data will change when the specified date range changes. However, the chart should always show 6 labels at max even if the date range changes, meaning, the data set changes (increases).
Now, I would like to know if this is possible directly in Chartjs where I add some funky option value to make it work automagically or, as I am working with PHP in the backend, there's a way in PHP where I can dynamically chunk these elements by only knowing the date range.
Please let me know if more explanation is required.
Any help would be appreciated.
PS: I have database access and I have all the data required to display in the chart, just need to display it in the said format.

You can use the tick callback to filter out ticks:
var options = {
type: 'bar',
data: {
labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange", "Red", "Blue", "Yellow", "Green", "Purple", "Orange", "Red", "Blue", "Yellow", "Green", "Purple", "Orange", "Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
datasets: [{
label: '# of Votes',
data: [12, 19, 3, 5, 2, 3, 12, 19, 3, 5, 2, 3, 12, 19, 3, 5, 2, 3, 12, 19, 3, 5, 2, 3],
backgroundColor: 'pink'
},
{
label: '# of Points',
data: [7, 11, 5, 8, 3, 7, 7, 11, 5, 8, 3, 7, 7, 11, 5, 8, 3, 7, 7, 11, 5, 8, 3, 7],
backgroundColor: 'lime'
}
]
},
options: {
scales: {
x: {
ticks: {
callback: function(value, index, values) {
let skips = values.length / 6;
return index % skips === 0 ? this.getLabelForValue(value) : ''
}
}
}
}
}
}
var ctx = document.getElementById('chartJSContainer').getContext('2d');
new Chart(ctx, options);
<body>
<canvas id="chartJSContainer" width="600" height="400"></canvas>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.5.0/chart.js"></script>
</body>

Related

PHP Collection flatten object only if it contains a key

I want to flatten some items in an array if they contain a key of items so for example the following object:
{
"key1": {
"order": 1,
"name": "Test"
},
"group1": {
"order": 1,
"name": "Test",
"items": {
"key2": {
"order": 1,
"name": "Test"
},
"key3": {
"order": 1,
"name": "Test"
}
}
}
}
Should be flattened to be formatted like follows, so basically removing the items within the group to the root level:
{
"key1": {
"order": 1,
"name": "Test"
},
"key2": {
"order": 1,
"name": "Test"
},
"key3": {
"order": 1,
"name": "Test"
}
}
I have put this object into a Illuminate\Database\Eloquent\Collection so I can use flatMap. flatten doesn't work, as I don't want to completely flatten it.
Assuming you are using Laravel, did you take a resource and collection in consideration? You could also try the Laravel collapse() method which can be found here: collapse method on collections
$collection = collect([
[1, 2, 3],
[4, 5, 6],
[7, 8, 9],
]);
$collapsed = $collection->collapse();
$collapsed->all();
// [1, 2, 3, 4, 5, 6, 7, 8, 9]

how to get each column of values as array directly, and without using pluck laravel?

hi trying to get the values of two columns as arrays, something like this
"result": {
"time": [1, 2, 4, 5, 6],
"values": [5, 6, 7, 8, 9]
}
i was able to do it using:
$result['result'] = DB::table(TimeSignal::getTableName())->select([
'value',
DB::raw("(time * 0.001) as time")
])
->where('trip_id', $trip->id)
->where('signal_type_id', $timeSignalType->id)
->orderBy('time', 'asc')
->get();
then:
$timeSignalData = $result['result'];
$result['result']['time'] = $timeSignalData->pluck('time');
$result['result']['values'] = $timeSignalData->pluck('value');
but the pluck function taking so much time to make the objects as array is their some way to do this faster or can we do it form the query directly.
I think I can solve your problems with a macro I found in Refactoring to Collections.
Collection::macro('transpose', function () {
$items = array_map(function (...$items) {
return $items;
}, ...$this->values());
return new static($items);
});
Visually it's something like this:
[1,2] [1,3,5]
[3,4] => transpose => [2,4,6]
[5,6]
Get the values in a Collection
$queryCollection = DB::table(TimeSignal::getTableName())->select([
'value',
DB::raw("(time * 0.001) as time")
])
->where('trip_id', $trip->id)
->where('signal_type_id', $timeSignalType->id)
->orderBy('time', 'asc')
->get();
This is how it looks so far
# dump($queryCollection)
Illuminate\Support\Collection {
all: [
{
+"value": 5,
+"time": 1,
},
{
+"value": 6,
+"time": 2,
},
{
+"value": 7,
+"time": 4,
},
{
+"value": 8,
+"time": 5,
},
{
+"value": 9,
+"time": 6,
},
...
],
}
Map every row to an Array...
$rows = $queryCollection->map(function($item) {
return collect($item)->toArray();
}));
Now it looks like this
# dump($rows)
Illuminate\Support\Collection {
all: [
[
"value": 5,
"time": 1,
],
[
"value": 6,
"time": 2,
],
[
"value": 7,
"time": 4,
],
[
"value": 8,
"time": 5,
],
[
"value": 9,
"time": 6,
],
...
],
}
Now we transpose it.
$rows = $rows->transpose()
Which gives us
# dump($rows)
Illuminate\Support\Collection {
all: [
[
5,
6,
7,
8,
9
],
[
1,
2,
4,
5,
6,
],
]
}
And finally, we add the keys:
$result = collect(['values', 'time'])->combine($rows)
Which gives us, finally:
# dump($result)
Illuminate\Support\Collection {
all: [
"values" => [
5,
6,
7,
8,
9
],
"time" => [
1,
2,
4,
5,
6,
],
]
}
# dump($result['time'])
[
1,
2,
4,
5,
6,
]
# dump($result['values'])
[
5,
6,
7,
8,
9,
]
Less steps:
$queryCollection = DB::table(TimeSignal::getTableName())->select([
'value',
DB::raw("(time * 0.001) as time")
])
->where('trip_id', $trip->id)
->where('signal_type_id', $timeSignalType->id)
->orderBy('time', 'asc')
->get();
$result = collect(['values', 'time'])->combine($queryCollection->map(function ($item) {
return collect($item)->toArray();
})->transpose());

How to change order of columns while exporting CSV data in Datatables?

I have TableTools file version like below
File: TableTools.min.js
Version: 2.1.4
I have a scenario like below
I have a data-table with Export to Excel / CSV (from client side)
In data table I need columns in the order 0,1,2,3,4 and so on
While exporting into excel I need columns in the order 0,2,1,4,3.
Is that possible in Table Tools? If so could you please help me.
Edit
I have following code:
"oTableTools": {
"sSwfPath": "path/to/swf/copy_csv_xls_pdf.swf",
"aButtons": [
{
"sExtends": "collection",
"sButtonText": "Export",
"aButtons": [
{
"sExtends": "csv",
"sFileName": "Sample.csv",
"oSelectorOpts": {
page: 'current'
},
"mColumns": [1, 2, 3, 4, 5, 6, 7, 8, 9, 12, 13, 14, 15, 16],
"fnClick": function (nButton, oConfig, oFlash) {
//$(".DTTT_button_xls").trigger('click');
oTable.colReorder.order( [ 1, 2, 3, 4, 16, 6, 7, 8, 9, 12, 13, 14, 15 ] );
}
},
{
"sExtends": "xls",
"sFileName": "Sample.xls",
"oSelectorOpts": {
page: 'current'
},
"mColumns": [1, 2, 3, 4, 5, 6, 7, 8, 9, 12, 13, 14, 15, 16],
}
],
}
]
},
$("#ExportButton").on("Click", function (e) {
table.colReorder.order( [ 0,2,1,4,3 ] );
} );
There isn't any existing feature available in Datatables that can re-order columns while exporting them.
So I had to write a PHP code at server side and had generate `CSV' file from it.

Can't get the Highcharts x-axis date to work

I have searched the high and low in Stackoverflow for a fix on this date problem. I'm really struggling to get the date to display on the chart with the points being correctly set onto them.
Here is the JS Script:
$(document).ready(function() {
var options = {
chart: {
renderTo: 'drawing',
zoomType: 'x',
width: 900,
height: 222
},
exporting: {
enabled: true
},
title: {
text: url+' - '+keyword
},
credits: {
text: 'Testing',
href: ''
},
xAxis: {
type: 'datetime'
},
yAxis: [{
allowDecimals: false,
reversed: true,
title: {
text: 'Rankings'
}
},],
tooltip: {
crosshairs: true,
shared: true
},
series: [{}]
};
var url = "****/chart.php";
$.getJSON(url, function(data1){
options.series = data1;
var chart = new Highcharts.Chart(options);
});
});
This is what our PHP Script Generated for the JSON
[{"name":"Google Rank","data":[["Date.UTC(2013, 3, 08)",23],["Date.UTC(2013, 3, 05)",24],["Date.UTC(2013, 3, 04)",23],["Date.UTC(2013, 3, 03)",22],["Date.UTC(2013, 3, 02)",24],["Date.UTC(2013, 3, 01)",26],["Date.UTC(2013, 2, 31)",24],["Date.UTC(2013, 2, 30)",24],["Date.UTC(2013, 2, 29)",25],["Date.UTC(2013, 2, 28)",25],["Date.UTC(2013, 2, 27)",25],["Date.UTC(2013, 2, 26)",26],["Date.UTC(2013, 2, 25)",25],["Date.UTC(2013, 2, 24)",24],["Date.UTC(2013, 2, 23)",0],["Date.UTC(2013, 2, 22)",10],["Date.UTC(2013, 2, 21)",10],["Date.UTC(2013, 2, 20)",10],["Date.UTC(2013, 2, 19)",10],["Date.UTC(2013, 2, 18)",10],["Date.UTC(2013, 2, 17)",10],["Date.UTC(2013, 2, 16)",9],["Date.UTC(2013, 2, 15)",9],["Date.UTC(2013, 2, 14)",9],["Date.UTC(2013, 2, 13)",9]],"visible":true,"pointInterval":86400000,"showInLegend":true},{"name":"Bing Rank","data":[["Date.UTC(2013, 3, 08)",0],["Date.UTC(2013, 3, 05)",0],["Date.UTC(2013, 3, 04)",0],["Date.UTC(2013, 3, 03)",0],["Date.UTC(2013, 3, 02)",0],["Date.UTC(2013, 3, 01)",0],["Date.UTC(2013, 2, 31)",0],["Date.UTC(2013, 2, 30)",0],["Date.UTC(2013, 2, 29)",0],["Date.UTC(2013, 2, 28)",0],["Date.UTC(2013, 2, 27)",0],["Date.UTC(2013, 2, 26)",0],["Date.UTC(2013, 2, 25)",0],["Date.UTC(2013, 2, 24)",0],["Date.UTC(2013, 2, 23)",0],["Date.UTC(2013, 2, 22)",0],["Date.UTC(2013, 2, 21)",0],["Date.UTC(2013, 2, 20)",0],["Date.UTC(2013, 2, 19)",0],["Date.UTC(2013, 2, 18)",0],["Date.UTC(2013, 2, 17)",0],["Date.UTC(2013, 2, 16)",0],["Date.UTC(2013, 2, 15)",0],["Date.UTC(2013, 2, 14)",0],["Date.UTC(2013, 2, 13)",0]],"visible":true,"pointInterval":86400000,"showInLegend":true},{"name":"Yahoo Rank","data":[["Date.UTC(2013, 3, 08)",0],["Date.UTC(2013, 3, 05)",0],["Date.UTC(2013, 3, 04)",0],["Date.UTC(2013, 3, 03)",0],["Date.UTC(2013, 3, 02)",0],["Date.UTC(2013, 3, 01)",0],["Date.UTC(2013, 2, 31)",0],["Date.UTC(2013, 2, 30)",0],["Date.UTC(2013, 2, 29)",0],["Date.UTC(2013, 2, 28)",0],["Date.UTC(2013, 2, 27)",0],["Date.UTC(2013, 2, 26)",0],["Date.UTC(2013, 2, 25)",0],["Date.UTC(2013, 2, 24)",0],["Date.UTC(2013, 2, 23)",0],["Date.UTC(2013, 2, 22)",0],["Date.UTC(2013, 2, 21)",0],["Date.UTC(2013, 2, 20)",0],["Date.UTC(2013, 2, 19)",0],["Date.UTC(2013, 2, 18)",0],["Date.UTC(2013, 2, 17)",0],["Date.UTC(2013, 2, 16)",0],["Date.UTC(2013, 2, 15)",0],["Date.UTC(2013, 2, 14)",0],["Date.UTC(2013, 2, 13)",0]],"visible":true,"pointInterval":86400000,"showInLegend":true}]
In JSON you cannot use functions like Date.UTC(), so I advice to use timestamp number.

Populate javascript array with PHP array of Variables [duplicate]

This question already exists:
Closed 10 years ago.
Possible Duplicate:
Dynamic Pie Chart Data in Javascript and PHP
The following code is used to populate a pie chart in javascript:
<script type="text/javascript">
var agg = { label: 'Aggressive', pct: [60, 10, 6, 30, 14, 10] },
bal = { label: 'Balanced', pct: [24, 7, 2, 18, 13, 36] },
mod = { label: 'Moderate', pct: [12, 4, 2, 10, 11, 61] },
inc = { label: 'Income', pct: [ 0, 0, 0, 0, 0,100] },
</script>
Instead of tm: [40, 60, 67, 30, 74, 50] as seen above, I would like to make each of 6 values a php variable. Like: tm: [$r1, $r2, $r3, $r4, $r5, $r6] . How do I do this?
How do I do this with? A php array or json encode?
Yes, json_encode a PHP array:
var agg = <?php echo json_encode(array('label' => 'Aggressive', 'pct' => array($r1, $r2, ...))); ?>,
bal = <?php echo json_encode(...); ?>,
...

Categories