Create multi bar/ muli series highchart in laravel - javascript

I want to make a chart with multi series/ multi data with highcharts in laravel, but I always fails, this is my expectations
enter image description here
Tokyo, London, etc. there are replaced with the name of my product category
this is my controller:
<?php
namespace App\Http\Controllers;
use App\Models\Category;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use PHPUnit\TextUI\XmlConfiguration\Group;
class DashboardController extends Controller
{
public function index()
{
$category = Category::select('name')->pluck("name");
$total = Category::select(DB::raw("SUM(total) as total"))->GroupBy(DB::raw('MONTH(created_at)'))->pluck('total');
$bulan = Category::select(DB::raw("MONTHNAME(created_at) as bulan"))->GroupBy(DB::raw('bulan'))->pluck('bulan');
return view('admin.dashboard', compact('category', 'total', 'bulan'));
}
}
and this is html and javacript code
#section('content')
<h1 class="gray">Dashboard</h1>
<figure class="highcharts-figure">
<div id="container"></div>
<p class="highcharts-description">
A basic column chart compares rainfall values between four cities.
Tokyo has the overall highest amount of rainfall, followed by New York.
The chart is making use of the axis crosshair feature, to highlight
months as they are hovered over.
</p>
</figure>
#section('javascript')
<script src="https://code.highcharts.com/highcharts.js"></script>
<script src="https://code.highcharts.com/modules/exporting.js"></script>
<script src="https://code.highcharts.com/modules/export-data.js"></script>
<script src="https://code.highcharts.com/modules/accessibility.js"></script>
<script type="text/javascript">
let category = <?php echo json_encode($category) ?>;
let total = <?php echo json_encode($total) ?>;
let month = <?php echo json_encode($month) ?>;
console.log(category, total, month);
Highcharts.chart('container', {
chart: {
type: 'column'
},
title: {
text: 'Monthly Average Rainfall'
},
subtitle: {
text: 'Source: WorldClimate.com'
},
xAxis: {
// categories: ["Jan", "Feb", "Mar", "Apr", "Mei", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"],
caegories : month,
crosshair: true
},
yAxis: {
min: 0,
title: {
text: 'Rainfall (mm)'
}
},
tooltip: {
headerFormat: '<span style="font-size:10px">{point.key}</span><table>',
pointFormat: '<tr><td style="color:{series.color};padding:0">{series.name}: </td>' +
'<td style="padding:0"><b>{point.y:.1f} mm</b></td></tr>',
footerFormat: '</table>',
shared: true,
useHTML: true
},
plotOptions: {
column: {
pointPadding: 0.2,
borderWidth: 0
}
},
series: [{
name: category,
data: total
}]
});
</script>
#endsection
#endsection
and this is the result I get enter image description here

instead pluck it one by one just use one variable and setup query in it and parse it in the javascript :
so first one is set some query:
<?php
namespace App\Http\Controllers;
use App\Models\Category;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use PHPUnit\TextUI\XmlConfiguration\Group;
class DashboardController extends Controller
{
public function index()
{
$category = Category::select(
DB::raw("MONTHNAME(created_at) as bulan"),
DB::raw("SUM(total) as total1"),
DB::raw("SUM(total) as total2"),
DB::raw("SUM(total) as total3"),
)->groupBy('bulan')->get();
return view('admin.dashboard', compact('category'));
}
}
for the javascript do this :
Highcharts.chart('container', {
chart: {
type: 'column'
},
title: {
text: 'Monthly Average Rainfall'
},
subtitle: {
text: 'Source: WorldClimate.com'
},
xAxis: {
categories: [
#php
foreach($category as $categories){
echo "'$categories->bulan',";
}
#endphp
],
crosshair: true
},
yAxis: {
min: 0,
title: {
text: 'Rainfall (mm)'
}
},
tooltip: {
headerFormat: '<span style="font-size:10px">{point.key}</span><table>',
pointFormat: '<tr><td style="color:{series.color};padding:0">{series.name}: </td>' +
'<td style="padding:0"><b>{point.y:.1f} mm</b></td></tr>',
footerFormat: '</table>',
shared: true,
useHTML: true
},
plotOptions: {
column: {
pointPadding: 0.2,
borderWidth: 0
}
},
series: [{
name: 'Total1',
data: [ #php
foreach($category as $categories){
echo "'$categories->total1',";
}
#endphp]
}, {
name: 'Total2',
data: [ #php
foreach($category as $categories){
echo "'$categories->total2',";
}
#endphp]
}, {
name: 'total3',
data: [ #php
foreach($category as $categories){
echo "'$categories->total3',";
}
#endphp]
}]
});
the point is just parse the query with foreach in each properties like this:
[ #php
foreach($category as $categories){
echo "'$categories->total1',";
}
#endphp]
Hope it helps i'm from indonesia also wkwk

Related

Dynamic Chart Rendering in Razor View

I've data grouping in C# and trying to bind it from Razor view as follows with high charts:
//Dynamic Chart - Starts
#if (Model.aLstTopsideModuleGroupBy.ToList().Count > 0)
{
foreach (var item in Model.aLstTopsideModuleGroupBy)
{
foreach (var item2 in item)
{
int i = 0;
<text>
Highcharts.chart('container'#i, {
chart: {
type: 'column'
},
title: {
text: 'Demo Chart'
},
subtitle: {
text: ''
},
xAxis: {
categories: [
'Structural Primary',
'Structural Secondary',
'Mechanical',
'Piping',
'Electrical',
'Instrument',
'Telecommunication',
'Safety',
'Architectural ',
'Other/ Future Load ',
'Live Load'
],
crosshair: true
},
yAxis: {
min: 0,
title: {
text: 'Weight Data'
}
},
tooltip: {
headerFormat: '<span style="font-size:10px">{point.key}</span><table>',
pointFormat: '<tr><td style="color:{series.color};padding:0">{series.name}: </td>' +
'<td style="padding:0"><b>{point.y:.1f}</b></td></tr>',
footerFormat: '</table>',
shared: true,
useHTML: true
},
plotOptions: {
column: {
pointPadding: 0,
borderWidth: 0
}
},
series: [
{
name: 'Dry',
data: '#item2.BaseDry'
}, {
name: 'Operating',
data: '#item2.BaseOp'
}]
});
</text>
i++;
}
}
}
//Dynamic Chart - Ends
The data grouping is something as follows:
Data 1
1, 2, 3, 4, 5
Data 2
1, 2, 3, 4, 5
The above I require to create two different charts depending upon the data set, that's why used the followg:
Highcharts.chart('container'#i, {});
In the frontend, trying to do the following:
<div class="container-fluid">
<div class="row">
<div class="col-sm-12 col-lg-12 col-md-12 col-xs-12">
#if (Model.aLstTopsideModuleGroupBy.ToList().Count > 0)
{
int i = 0;
foreach (var item in Model.aLstTopsideModuleGroupBy)
{
<div id="container" #i></div>
<p class="highcharts-description">
</p>
}
i++;
}
</div>
</div>
</div>
In the browser's inspect element, getting this exception:
Uncaught SyntaxError: missing ) after argument list
I was trying to follow this link but failed - Razor With JavaScript
Is there any way I can make the chart dynamic with Razor view rather Ajax call? This is what I am trying to implement:
High Charts
When using razon and javascript you need to be mindful that you can't really generate javascript code using razor. To the best of my knowledge you need to create a javascript function in the same view or a parent view if you are using a partial that creates the charts and have razor call it along with creating the div placeholder to display the chart, the data on the chart should be loaded via ajax calls.
The following code is an example and should not be copy and pasted without modification, you need to tweak it for your requirements, this is only to show the concept. If anyone else has a more elegant solution, please contribute.
async function createChart(containerName, dryArgument, operatingArgument){
let dryData = await fech(`#Url.Action("GetDryData")/?argument=${dryArgument}`)
let operatingData = await fech(`#Url.Action("GetOperatingData")/?argument=${operatingArgument}`)
Highcharts.chart(containerName, {
chart: {
type: 'column'
},
title: {
text: 'Monthly Average Rainfall'
},
subtitle: {
text: 'Source: WorldClimate.com'
},
xAxis: {
categories: [
'Jan',
'Feb',
'Mar',
'Apr',
'May',
'Jun',
'Jul',
'Aug',
'Sep',
'Oct',
'Nov',
'Dec'
],
crosshair: true
},
yAxis: {
min: 0,
title: {
text: 'Rainfall (mm)'
}
},
tooltip: {
headerFormat: '<span style="font-size:10px">{point.key}</span><table>',
pointFormat: '<tr><td style="color:{series.color};padding:0">{series.name}: </td>' +
'<td style="padding:0"><b>{point.y:.1f} mm</b></td></tr>',
footerFormat: '</table>',
shared: true,
useHTML: true
},
plotOptions: {
column: {
pointPadding: 0.2,
borderWidth: 0
}
},
series: [
{
name: 'Dry',
data: JSON.parse(dryData)
}, {
name: 'Operating',
data: JSON.parse(operatingData)
}]
});
}
Note that you need to create two ContenResult() actions in the controller to get the data.
To call them you can then use:
<div class="container-fluid">
<div class="row">
<div class="col-sm-12 col-lg-12 col-md-12 col-xs-12">
//Dynamic Chart - Starts
#if (Model.aLstTopsideModuleGroupBy.ToList().Count > 0)
{
foreach (var item in Model.aLstTopsideModuleGroupBy)
{
foreach (var item2 in item)
{
int i = 0;
<div id="container#i"></div>
<p class="highcharts-description">
</p>
<script>
window.onload = function () {
createChart('#container#i',#item2.BaseDry,#item2.BaseOp);
};
</script>
i++;
}
}
}
//Dynamic Chart - Ends
</div>
</div>
</div>

how to make chart real time with 2 line and get data from php with highcharts

hello i want make chart with use php for get my data
here my script
series: [{
name: 'Random data',
data: [<?php echo $row['rx-bits-per-second'] ?>]
},
{
name: 'Random data',
data: [<?php echo $row['tx-bits-per-second'] ?>]
}]
full script highcharts here :
$(document).ready(function()
{
$('#dataTable').DataTable();
});
</script>
<script>
$(function () {
$(document).ready(function() {
Highcharts.setOptions({
global: {
useUTC: false
}
});
var chart;
$('#container').highcharts({
chart: {
type: 'spline',
animation: Highcharts.svg, // don't animate in old IE
marginRight: 10,
events: {
load: function() {
// set up the updating of the chart each second
var series = this.series[0];
var series2 = this.series[1];
setInterval(function() {
var x = (new Date()).getTime(), // current time
y = Math.random();
z = Math.random();
series.addPoint([x, y], false, true);
series2.addPoint([x, z], true, true);
}, 1000);
}
}
},
title: {
text: 'Live random data'
},
xAxis: {
type: 'datetime',
tickPixelInterval: 150
},
yAxis: [{
title: {
text: 'Value1'
},
plotLines: [{
value: 0,
width: 1,
color: '#808080'
}]
},
{
title: {
text: 'Value2'
},
plotLines: [{
value: 0,
width: 1,
color: '#808080'
}]
}],
tooltip: {
formatter: function() {
return '<b>'+ this.series.name +'</b><br/>'+
Highcharts.dateFormat('%Y-%m-%d %H:%M:%S', this.x) +'<br/>'+
Highcharts.numberFormat(this.y, 2);
}
},
legend: {
enabled: false
},
exporting: {
enabled: false
},
series: [{
name: 'Random data',
data: [<?php echo $row['rx-bits-per-second'] ?>]
},
{
name: 'Random data',
data: [<?php echo $row['tx-bits-per-second'] ?>]
}]
});
});
});
and point for get data here <?php echo $row['tx-bits-per-second'] ?>
but line from chart show null. can you help me?
Thanks.
In that 'source' object, remove the PHP for now and add simple values like in the highcharts examples. Make sure that is solid before continuing.
Once you're sure, add single quotes around the php tags and try it again.
If it still has trouble I would do a "View Source" on the page to check if the 'data' properties in that 'source' object array were populated properly.
Hard to continue without knowing how that PHP comes out

Highcharts adding series for every selectbox selection

I'm using Highcharts with MySQL and PHP... I have a Selectbox (Multiple Selections allowed) which contains company sections.
What I'm trying to do is create a new chart series for every selection the user chooses.
Example: If I choose from selectbox "option1,option2,option3" ... the chart will have 3 series for these 3 selected options. However, If I chose only option1, the chart will have only 1 series.
My code so far:
<script type="text/javascript">
$(function () {
$('#container').highcharts({
title: {
text: 'Daily Volume of Calls',
x: -20 //center
},
xAxis: {
type: 'datetime'
},
plotOptions: {
series: {
pointStart: Date.UTC(<?php echo $datefixed; ?>),
pointInterval: 24 * 3600 * 1000 // one day
}
},
yAxis: {
title: {
text: 'Total Calls'
},
plotLines: [{
value: 0,
width: 1,
color: '#808080'
}]
},
tooltip: {
valueSuffix: ' Calls'
},
legend: {
layout: 'vertical',
align: 'right',
verticalAlign: 'middle',
borderWidth: 0
},
series: [{
name: <?php echo $firstselection ?>,
data: [<?php echo join($callsarray, ',') ?>]
}, {
name: <?php echo $secondselection ?>, //**<<< THE PROBLEM IS HERE**
showInLegend: true,
data: []
}]
});
The problem on my code is if the variable $secondselection is empty or not set(meaning the user didn't chose more than 1 option), the chart will return a blank page even if $firstselection variable is set. But if the user chooses a second option, it will show fine.
Any help guys? :)

How to include strings in series data to pull for tooltip point formatting?

beginner here, I'm trying to build a column graph that shows a username on the x axis, and a test score on the y axis. In the tooltips box, I'm trying to make it so it shows the test score and the date the test was taken. I'm using PHP to populate the graph based on an oracle sql database, so I'm mixing PHP into my javascript for Highcharts.
I'm not sure if what I'm trying to do is actually possible, but I'm trying to take the test date from the sql database, and plug it into the series data, so I can call it out into the tooltips box (that way when you hover over the column, it'll tell you the user, the score, and the date they took the exam).
This is what I'm trying, and it isn't working, because I'm guessing series data has something against strings instead of numeric. Any help you can offer would be awesome! Thanks!
<br><br><br><br>
<div id="graph1" style="height: 400px; width: <?php echo $chartspace ?>px"></div>
<input id="width" type="range" value="<?php echo $chartspace ?>" min="300" max="<?php echo $chartspacemax ?>" />
<script>
$(function () {
$('#graph1').highcharts({
credits: { enabled:false},
chart: {
type: 'column'
},
title: {
text: 'Most Recent Test Scores'
},
subtitle: {
text: 'Drag slider to change the chart width'
},
xAxis: {
categories: [
<?php
$i = 0;
do {
echo "'";
echo $userinfos[$i]['username'];
echo "',";
$i++;
} while ($i<=$count); ?>
]
},
yAxis: {
plotLines: [{
color: 'red',
dashStyle: 'shortdash',
value: 85,
width: 1,
}],
floor: 0,
ceiling: 100,
title: {
text: 'Test Score (%)'
}
},
series: [{
showInLegend: false,
name: 'Test Score',
data: [
<?php
$i = 0;
do {
if($userinfos[$i]['score'] >= 85){
echo "{y:";
echo $userinfos[$i]['score'];
echo ", testdate:";
echo $userinfos[$i]['most_recent_test_date'];
echo ", color: '#00A6CF'},";}
else{
echo "{y:";
echo $userinfos[$i]['score'];
echo ", testdate:";
echo $userinfos[$i]['most_recent_test_date'];
echo ", color: 'red'},";}
$i++;
} while ($i<=$count-1); ?>]
}],
tooltip: {
shared: true,
useHTML: true,
pointFormat: '<tr><td style="color: {series.color}">Score: </td>' +
'<td style="text-align: right">{point.y} %</td></tr><tr><br><td>Date: </td>' +
'<td style="text-align: right">{point.testdate}</td></tr>'
}
});
$('#width').bind('input', function () {
$('#graph1').highcharts().setSize(this.value, 400, false);
});
});
</script>
What you're trying to do should definitely be possible. Here's an example of that working:
http://jsfiddle.net/thfbx7gb/
However, in this case I pulled out the PHP and replaced it with some hard-coded data.
data: [{y:7, color: '#00A6CF', testdate: '2014-12-12'},{y:2, color:"#FF0000", testdate: '2015-01-03'}, {y:3,color:"#00FF00", testdate:'2014-10-19'}]
So I think the problem is that you're mixing in PHP with javascript and getting some strange results. It's generally a very bad idea to include inline PHP into javascript code like you're doing if for no other reason that it's really, really hard to read and debug.
A few things jump out at me:
You shouldn't be using PHP for this at all, but if you must then you shouldn't be using do-while loops like you are. You're using a do/while with an incrementor instead of a for loop:
$i = 0;
do {
echo "'";
echo $userinfos[$i]['username'];
echo "',";
$i++;
} while ($i<=$count);
This should really be:
for ($i=0; $i<=$count; $i++) {
echo "'{$userinfos[$i]['username']}'";
}
You should be able to see how the other do/while loops you're using could be reduced to a much more succinct for loop.
But that still doesn't eliminate the whole problem of including PHP code in your javascript. You should really be either hard coding this data or loading it from an external source of some kind. The typical way of doing that would be with an AJAX call to load the data and then pass that in to the chart directly.
You would have a file that generates the data object directly and outputs that as as JSON string using json_ecode();
$output = array();
foreach ($userinfos as $user) {
$output['categories'][] = $user['username'];
if ($user['score'] >= 85) {
$color = "#00A6CF";
} else {
$color = "#FF0000";
}
$user['color'] = $color;
$output['seriesdata'][] = $user;
}
echo json_encode($output);
This should give you a JSON object which you can read work with pretty easily. Something along the lines of this (which is untested, it may not work without a bit of fiddling):
$.getJSON('/generate.php', function(data) {
$('#graph1').highcharts({
credits: { enabled:false},
chart: {
type: 'column'
},
title: {
text: 'Most Recent Test Scores'
},
subtitle: {
text: 'Drag slider to change the chart width'
},
xAxis: {
categories: data.categories
yAxis: {
plotLines: [{
color: 'red',
dashStyle: 'shortdash',
value: 85,
width: 1,
}],
floor: 0,
ceiling: 100,
title: {
text: 'Test Score (%)'
}
},
series: [{
showInLegend: false,
name: 'Test Score',
data: data.seriesdata,
tooltip: {
shared: true,
useHTML: true,
pointFormat: '<tr><td style="color: {series.color}">Score: </td>' +
'<td style="text-align: right">{point.y} %</td></tr><tr><br><td>Date: </td>' +
'<td style="text-align: right">{point.testdate}</td></tr>'
}
});
});

Creating graph on webpage using Highcharts

I need to create a bargraph on my webpage using Highcharts. I am using the following code but nothing is displayed. I am new to scripting webpages so I am not sure what is wrong.
<div id="container1" style="width:100%; height:400px;"></div>
function create_graph(graph) {
chart = new Highcharts.Chart ({
chart: {
height: 600,
width: 1200,
renderTo: container1,
type: 'column'
//reflow: false
},
title: {
text: graph["graphTitle"]
},
xAxis: {
categories: graph["xAxisLabels"]
},
yAxis: {
min: 0,
title: {
text: graph["yaxisTitle"]
}
},
tooltip: {
headerFormat: '<span style="font-size:10px">{point.key}</span><table>',
pointFormat: '<tr><td style="color:{series.color};padding:0">{series.name}: </td>' +
'<td style="padding:0"><b>{point.y}</b></td></tr>',
footerFormat: '</table>',
shared: true,
useHTML: true
},
plotOptions: {
column: {
pointPadding: 0.2,
borderWidth: 0
}
},
series: generateLineData(graph)
});
}
graph = {"graphTitle": "Title" ,"xAxisLabels" : xAxisLabels, "xAxisTitle" : "Properties", "yAxisTitle" : "Average percentile", "yAxisValues" : array1}
You must have the javascript vars xAxisLabels , array1 initialized before creating object graph. Then, of course, following the logic of your code, you should have a call to create_graph(graph);. Finally, your generateLineData() function should look like the following:
function generateLineData(g) {
return [{ data: g["yAxisValues"] }];
}
if all these premises are fulfilled, then your graph should be displayed. You can verify it at this jsfiddle demo: http://jsfiddle.net/tgnu5941/2/

Categories

Resources