Morris chart with for looped data - javascript

I have a morris chart in my code. I get data to the chart as following.
$(document).ready(function(){
$("#month_search").click(function(){
var month_value = $("#month_value").val();
$.ajax({
url: '../../new/seller.php',
type: 'POST',
data: {flag: '4', month_value: month_value},
success: function(data) {
alert(data);
var data_json = JSON.parse(data);
var total_chart = {};
for(i = 0; i < data_json.RESULT.length; i++){
var total_all = parseInt(data_json.RESULT[i].total_cus) + parseInt(data_json.RESULT[i].new_cus);
total_chart=
[{
category: data_json.RESULT[i].cat_name,
value: total_all
}] ;
}
var chart1= Morris.Bar({
element: 'morris-bar-chart',
data:total_chart,
xkey: 'category',
ykeys: ['value'],
labels: ['total customers'],
hideHover: 'auto',
resize: true
});
},
});
});
});
But when showing the chart, only last category is shown. (there are 10 categories in the loop).
How to show all these categories in the chart. Please help.

Related

Show values in Bar chart javascript

I would really appreciate if you could help me with this problem.
I need to be able to show the values at the top of the bars that were drawn, that is to say that they are not only seen when the mouse passes over the bar, but show the static values.
This is the final chart:
And, this is my code:
success: function(response){
$("#myChart2").remove();
$("#Grafica2").append('<canvas id="myChart2"></canvas>');
var obj = JSON.parse(response);
var labels = [];
var colors = [];
var values = [];
for(var i in obj){
colors.push(getRandomColor())
labels.push(obj[i].TipoConsult)
values.push(obj[i].PzsTotal)
}
new Chart(document.getElementById("myChart2"), {
type: 'bar',
data: {
labels: labels,
datasets: [
{
label: "Total piezas scrap generadas",
backgroundColor: colors,
data: values
}
]
},
options: {
legend: { display: false },
title: {
display: true,
text: 'Total de piezas scrap generadas por "'+TipoConsulta+'" entre las fechas '+FechaMin+' y '+FechaMax
}
}
});
}

Chart.js - how to have statis lables and populate with dynamic data?

I am working on chart.js and I have data coming from JSON via ajax. See the example below:
[{"timestamp":"06:00:00.000000","true_count":2},{"timestamp":"07:00:00.000000","true_count":5},{"timestamp":"08:00:00.000000","true_count":7},{"timestamp":"09:00:00.000000","true_count":8},{"timestamp":"10:00:00.000000","true_count":12},{"timestamp":"11:00:00.000000","true_count":15},{"timestamp":"12:00:00.000000","true_count":20},{"timestamp":"13:00:00.000000","true_count":17},{"timestamp":"14:00:00.000000","true_count":14},{"timestamp":"16:00:00.000000","true_count":11},{"timestamp":"17:00:00.000000","true_count":19},{"timestamp":"18:00:00.000000","true_count":22},{"timestamp":"19:00:00.000000","true_count":16},{"timestamp":"20:00:00.000000","true_count":14},{"timestamp":"22:00:00.000000","true_count":7}]
The JS code i am using for my chart is below:
// create initial empty chart
var ctx_live = document.getElementById("chLine");
var myChart = new Chart(ctx_live, {
type: 'bar',
data: {
labels: [],
datasets: [{
data: [],
borderWidth: 1,
borderColor:'#00c0ef',
label: 'liveCount',
}]
},
options: {
responsive: true,
title: {
display: true,
text: "Count Per Hour",
},
legend: {
display: false
},
scales: {
yAxes: [{
ticks: {
beginAtZero: true,
}
}]
}
}
});
// logic to get new data
var getData = function() {
var _data =[];
var _labels = [];
$.ajax({
url: 'chart_data',
type: "get",
success: function(data) {
full_data = JSON.parse(data);
full_data.forEach(function(key,index) {
_data.push(key.true_count);
_labels.push(key.hour);
});
myChart.data.labels = _labels;
myChart.data.datasets[0].data = _data;
myChart.update();
}
});
};
// get new data every 3 seconds
setInterval(getData, 3000);
Now, this is working fine and shows the true_count over time which is a one-hour basis. Now, the chart is showing only hours with count but what I would like to do is to set the static hours from 12 AM to 11 PM, and for hours for which I don't have data the true_count will be zero, and for those that I have data for, the true count will be assigned to that hour and show on the chart.
Any ideas on how do I do that?
Here is an example:
// create initial empty chart
var ctx_live = document.getElementById("chLine");
var myChart = new Chart(ctx_live, {
type: 'bar',
data: {
labels: [],
datasets: [{
data: [],
borderWidth: 1,
borderColor: '#00c0ef',
label: 'liveCount',
}]
},
options: {
responsive: true,
title: {
display: true,
text: "Count Per Hour",
},
legend: {
display: false
},
scales: {
yAxes: [{
ticks: {
beginAtZero: true,
}
}]
}
}
});
// Some constants to be changed later:
const HOUR_TO_START = 0;
const HOUR_TO_END = 23;
// helper:
const intToAmPm = (i) =>
i==0 ? '12 AM' :
i==12 ? '12 PM' :
i < 12 ? i + ' AM' :
(i-12) + ' PM';
// logic to get new data
var getData = function() {
var _data = [];
var _labels = [];
$ajax({
url: 'chart_data',
type: "get",
success: function(data) {
full_data = JSON.parse(data);
let preparedData = {};
full_data.forEach(function(key, index) {
let hour = parseInt(String(key.timestamp).substring(0, 2));
preparedData[hour] = key.true_count;
});
for (let i = HOUR_TO_START; i <= HOUR_TO_END; i++) {
_data.push(preparedData[i] === undefined ? 0 : preparedData[i]);
_labels.push(intToAmPm(i));
}
myChart.data.labels = _labels;
myChart.data.datasets[0].data = _data;
myChart.update();
}
});
};
// get new data every 3 seconds
//setInterval(getData, 3000);
getData();
// THIS IS FOR TESTING. IMITATE BACKEND
function $ajax(param) {
param.success('[{"timestamp":"06:00:00.000000","true_count":2},{"timestamp":"07:00:00.000000","true_count":5},{"timestamp":"08:00:00.000000","true_count":7},{"timestamp":"09:00:00.000000","true_count":8},{"timestamp":"10:00:00.000000","true_count":12},{"timestamp":"11:00:00.000000","true_count":15},{"timestamp":"12:00:00.000000","true_count":20},{"timestamp":"13:00:00.000000","true_count":17},{"timestamp":"14:00:00.000000","true_count":14},{"timestamp":"16:00:00.000000","true_count":11},{"timestamp":"17:00:00.000000","true_count":19},{"timestamp":"18:00:00.000000","true_count":22},{"timestamp":"19:00:00.000000","true_count":16},{"timestamp":"20:00:00.000000","true_count":14},{"timestamp":"22:00:00.000000","true_count":7}]');
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.min.js"></script>
<canvas id="chLine"></canvas>

Inserting data from controller to an array in javascript

I try to create a graph using Chart.js and get the data from database, but I am confused how to pass the data to an array variable in view.
This is the Controller
public function ApiLaporanBulanan()
{
$data = DB::table("transaksipenjualan")->select(DB::raw('EXTRACT(MONTH FROM tanggaltransaksi) AS Bulan, SUM(total) as Pendapatan'))
->groupBy(DB::raw('EXTRACT(MONTH FROM tanggaltransaksi)'))
->get();
return response()->json($data);
//Accessing Data
dd($data[0]->Bulan);
}
This is the script in view
<script>
var url = "{{url('laporan/pendapatanAPI')}}";
var Bulan = [];
var Pendapatan = [];
$(document).ready(function(){
$.get(url, function(response){
response.forEach(function(data){
Bulan.push(data->Bulan);
Pendapatan.push(data->Pendapatan);
});
var ctx = document.getElementById("canvas").getContext('2d');
var myChart = new Chart(ctx, {
type: 'bar',
data: {
labels: Bulan,
datasets: [{
label: 'Nilai Pendapatan',
data: Pendapatan,
borderWidth: 1
}]
},
options: {
scales: {
yAxes: [{
ticks: {
beginAtZero:true
}
}]
}
}
});
});
});
</script>
You can create two array in your controller.
$label = [];
$dataset = [];
and loop through your collection and push data to these arrays
foreach($data as $value){
$label[] = $value->data_field;
$dataset[] = $value->data_field;
}
And pass it to your blade and assign these array to your chart
...
var myChart = new Chart(ctx, {
type: 'bar',
data: {
labels: Bulan,
datasets: [{
label: 'Nilai Pendapatan',// label data
data: Pendapatan, // dataset
borderWidth: 1
}]
},
....

how to create line chart with jqplot using ajax data

I am trying to create line chart with Jqplot by getting the data from c# controller using ajax.
function getGraph(fcn) {
var turl = '/Rep/ChartBoxPlot/' + fcn;
$.ajax({
type: "POST",
url: turl,
dataType: "json",
success: function (result) {
$('#chart1').empty();
for (var i = 0; i < result.length; i++) {
var temp = result[i]['Date'];
var date = moment(temp).format('MMM DD');
var y = result[i]['Actual'];
var line1 = [date, result[i]['Actual']];
var line2 = [date, result[i]['Forecast']];
// alert(line1);
var plot = $.jqplot('chart1', [line1], {
axes: {
xaxis: {
label: "Forecast",
renderer: $.jqplot.ajaxDataRenderer,
//tickOptions: { formatString: '%I:%M:%S %p' },
//numberTicks: 8,
tickInterval: '15 second'
},
yaxis: {
label: 'Lines'
},
},
});
}
},
error(result) {
alert(result)
}
});
}
html
<div id="chart1" style="height: 400px; width: 900px;
position: relative;" class="jqplot-target">
The data from controller is coming fine but the graph is not plotted. Any suggestions would be appreciated
Thanks

How to show legends on chart using c3 js with json

I'm using C3 chart to present some data on my project and I want to show up legends (Label in my case) instead of numbers in the AcisX :
Data json format :
[
{"Label":"DQUA","Aut":3.75,"NoAut":3.75,"CM":32},
{"Label":"DPRO","Aut":43.9,"NoAut":0,"CM":144},
{"Label":"DMAI","Aut":1.6999999999999993,"NoAut":0,"CM":0},
{"Label":"DENG","Aut":0,"NoAut":0,"CM":16}
]
My attempt to get the task work :
var chart = c3.generate({
bindto: '.ks-chart-orders-block',
data: {
url: '/Home/AbsencesByDepartementFiltredByReasons',
mimeType: 'json',
type:'bar',
keys:{
value: ['Aut','NoAut','CM']
},
}
}
});
Getted Result :
Expected Result:
You need to modify the x-axis with a custom category:
var chart = c3.generate({
bindto: '.ks-chart-orders-block',
data: {
url: '/Home/AbsencesByDepartementFiltredByReasons',
mimeType: 'json',
type:'bar',
keys:{
x: 'Label',
value: ['Aut','NoAut','CM']
},
},
axis: {
x: {
type: 'category',
tick: {
centered: true
}
}
}
});

Categories