How to configure linear labels in Time Cartesian Chartjs? - time

I need to show labels on the x-axis every 2 hours (0h, 2h, 4h...). What am I missing?
<script>
var ctx = document.getElementById('myChart').getContext('2d');
var myChart = new Chart(ctx, {
type: 'line',
data: {
//labels: ['0h', '2h', '4h', '6h', '8h', '10h', '12h', '14h', '16h', '18h', '20h', '22h', '0h'],
datasets: [{
label: 'AAA1111',
//xAxisID: 'Hora',
//yAxisID: 'Velocidade',
data: [{
t: new Date("2015-3-15 12:30"),
y: 12
},
{
t: new Date("2015-3-15 14:40"),
y: 45
},
{
t: new Date("2015-3-15 17:50"),
y: 77
}
],
borderColor: 'rgba(255, 0, 0, 1)',
borderWidth: 4,
fill: false,
lineTension: 0,
lineJoint: "round",
spanGaps: true
}]
},
options: {
scales: {
xAxes: [{
type: 'time',
distribution: 'linear',
time: {
unit: 'hour',
//stepSize: 24??
},
ticks: {
source: 'data'
}
}]
}
}
});
</script>
The chart plots Time x Velocity.

Two small changes will achieve the desired result:
set stepSize: 2 to 'show labels on X axis every 2 hours (0h, 2h, 4h...)'
remove ticks: { source: 'data' } as that:
generates ticks from data (including labels from data {t|x|y} objects)"
Here's a working example based on the posted code:
var ctx = document.getElementById('myChart').getContext('2d');
var myChart = new Chart(ctx, {
type: 'line',
data: {
//labels: ['0h', '2h', '4h', '6h', '8h', '10h', '12h', '14h', '16h', '18h', '20h', '22h', '0h'],
datasets: [{
label: 'AAA1111',
//xAxisID: 'Hora',
//yAxisID: 'Velocidade',
data: [{
t: new Date("2015-3-15 12:30"),
y: 12
},
{
t: new Date("2015-3-15 14:40"),
y: 45
},
{
t: new Date("2015-3-15 17:50"),
y: 77
}
],
borderColor: 'rgba(255, 0, 0, 1)',
borderWidth: 4,
fill: false,
lineTension: 0,
lineJoint: "round",
spanGaps: true
}]
},
options: {
scales: {
xAxes: [{
type: 'time',
distribution: 'linear',
time: {
unit: 'hour',
stepSize: 2
}
}]
}
}
});
<script src="https://cdn.jsdelivr.net/npm/chart.js#2.9.3/dist/Chart.bundle.min.js"></script>
<canvas id="myChart"></canvas>

Related

chartJS not showing the data

I am new to Laravel and ChartJS. Working on home project for farm management. I need to show annual milk generation ( monthwise) in chart. While Trying to show data in chartJS but not able to show the same.
The code is as below.
Data for Chart
var buffalototalmilkannual = JSON.parse('{!! json_encode($annualmilkrecord) !!}');
var monthsforbuffalototalmilkannual = JSON.parse('{!! json_encode($getmonths) !!}'); // Annual dates on x axis
//console.log(buffalototalmilkannual);
Chart
$(function () {
'use strict'
var annualbuffaloidmilkCanvas = $('#buffaloidmilkchartforyear').get(0).getContext('2d')
var annualbuffaloidmilkdata = {
labels: monthsforbuffalototalmilkannual,
datasets: [
{
label: 'Total Milk Prodcued',
backgroundColor: 'rgba(40, 167, 69, 0.9)',
borderColor: 'rgba(40, 167, 69, 0.8)',
pointRadius: false,
pointColor: '#3b8bba',
pointStrokeColor: 'rgba(40, 167, 69, 1)',
pointHighlightFill: '#fff',
pointHighlightStroke: 'rgba(40, 167, 69, 1)',
fill: false,
tension: 0.1,
pointRadius: 3,
data: 'buffalototalmilkannual',
},
]
}
var annualbuffaloidmilkOptions =
{
maintainAspectRatio: false,
responsive: true,
legend: { display: true },
scales:
{
xAxes: [{
gridLines: {
display: true,
},
type: 'time',
time: {
unit: 'month',
tooltipFormat: 'M Y'
}
}],
yAxes: [{
gridLines: {
display: true,
},
scaleLabel: {
display: true,
labelString: 'Milk in Liter'
},
ticks: {
suggestedMin: 0,
suggestedMax: 50
}
}],
},
tooltips: {enabled: true},
}
// This will get the first returned node in the jQuery collection.
// eslint-disable-next-line no-unused-vars
var salesChart = new Chart(annualbuffaloidmilkCanvas,
{
type: 'line',
data: annualbuffaloidmilkdata,
options: annualbuffaloidmilkOptions
}
)
})
Console.log file
Array(12)
0: "12.00"
1: "11.75"
2: 0
3: 0
4: 0
5: 0
6: 0
7: 0
8: 0
9: 0
10: 0
11: 0
length: 12
Did i miss something. Same code is working in another blade file for other data.
Thanks in Advance

how to display multiple sum with chart js and laravel?

I have three table
Table drics
Table country_dric
Table Countries
I just display country name with sum legal from table drics.
I want to display sum column legal, illegal, applicant and mandatory from table drics with country name.
How to display the sum of each column from table drics?
my controller
$drics =DB::table('countries')
->join('country_dric','countries.id','country_dric.country_id')
->join('drics','drics.id','country_dric.dric_id')
->select('name',\DB::raw('sum(legal) as sum'))->groupby('name')
->whereYear('drics.created_at', $year)->get();
$dric_title=[];
$dric=[];
foreach ($drics as $key => $value) {
$dric_title[$key]=$value->name;
$dric[$key]=$value->sum;
}
return view('home.home', compact(' 'dric', 'dric_title'));
js Code
<script>
var ctx = document.getElementById('dric').getContext('2d');
var myChart = new Chart(ctx, {
type: 'bar',
data: {
labels: #json($dric_title),
datasets: [{
label: '# ',
data: #json($dric),
backgroundColor: "rgba(0,31,68,0.8)",
borderColor: "rgb(167, 105, 0)",
borderWidth: 1,
}]
},
options: {
scales: {
yAxes: [{
ticks: {
beginAtZero: true
}
}]
}
}
});
</script>
Try this
Your controller:
$drics =DB::table('countries')
->join('country_dric','countries.id','country_dric.country_id')
->join('drics','drics.id','country_dric.dric_id')
->select('name',\DB::raw('sum(legal) as legal_sum')
,\DB::raw('sum(ilegal) as ilegal_sum')
,\DB::raw('sum(applicant) as applicant_sum')
,\DB::raw('sum(mandatory) as mandatory_sum'))->groupby('name')
->whereYear('drics.created_at', $year)->get();
$dric_title=[];
$dric=[];
foreach ($drics as $key => $value) {
$dric_title[$key]=$value->name;
$dric['legal'][$key]=$value->legal_sum;
$dric['ilegal'][$key]=$value->ilegal_sum;
$dric['applicant'][$key]=$value->applicant_sum;
$dric['mandatory'][$key]=$value->mandatory_sum;
}
return view('home.home', compact(' 'dric', 'dric_title'));
js code:
<script>
var ctx = document.getElementById('dric').getContext('2d');
var myChart = new Chart(ctx, {
type: 'bar',
data: {
labels: #json($dric_title),
datasets: [{
label: 'Legal',
data: #json($dric['legal']),
backgroundColor: "rgba(0,31,68,0.8)",
borderColor: "rgb(167, 105, 0)",
borderWidth: 1,
}, {
label: 'Ilegal',
data: #json($dric['ilegal']),
backgroundColor: "rgba(0,31,68,0.8)", // Change the color to make it different
borderColor: "rgb(167, 105, 0)",
borderWidth: 1,
}, {
label: 'Applicant',
data: #json($dric['applicant']),
backgroundColor: "rgba(0,31,68,0.8)", // Change the color to make it different
borderColor: "rgb(167, 105, 0)",
borderWidth: 1,
}, {
label: 'Mandatory',
data: #json($dric['mandatory']),
backgroundColor: "rgba(0,31,68,0.8)", // Change the color to make it different
borderColor: "rgb(167, 105, 0)",
borderWidth: 1,
}]
},
options: {
scales: {
yAxes: [{
ticks: {
beginAtZero: true
}
}]
}
}
});
</script>
You can use #foreach loop if you want too

ChartJS: How to center monthly bars against a daily line chart?

I'm trying to display total monthly sales and daily stock level. This way you could easily see that you didn't have any sales a particular month because you had low stock. Monthly sales is a bar chart that should be in the center of each month (in between the ticks).
In order to get it close to the middle my data is using the 15th of each month as the date to center it. I would want to know if there is a better way to achieve this?
JSFiddle to play around with: https://jsfiddle.net/8Lydhpqc/3/
const dailyStock = [
{ x: "2017-08-02", y: 1 },
{ x: "2017-08-25", y: 3 },
{ x: "2017-09-10", y: 7 },
{ x: "2017-09-28", y: 0 },
{ x: "2017-10-02", y: 3 },
{ x: "2017-10-24", y: 2 },
{ x: "2017-11-01", y: 1 },
{ x: "2017-11-30", y: 0 },
];
//using the 15th of each month to center it
const monthlyTotal = [
{ x: "2017-08-15", y: 1 },
{ x: "2017-09-15", y: 10 },
{ x: "2017-10-15", y: 5 },
{ x: "2017-11-15", y: 5 },
];
var ctx = document.getElementById("myChart").getContext("2d");
var myChart = new Chart(ctx, {
type: "bar",
data: {
labels: ["2017-08", "2017-09", "2017-10", "2017-11"],
datasets: [
{
label: "sales",
data: data,
backgroundColor: "green",
borderColor: "black",
borderWidth: 1,
order: 2,
},
{
label: "stock",
type: "line",
data: dailyStock,
backgroundColor: "orange",
borderColor: "orange",
fill: false,
order: 1,
},
],
},
options: {
scales: {
xAxes: [
{
type: "time",
time: {
unit: "month",
displayFormats: {
month: "MMM",
},
},
distribution: "linear",
},
],
yAxes: [
{
ticks: {
beginAtZero: true,
},
},
],
},
},
});
Welcome to Stackoverflow!
It seems that there is a way better than using the 15th of the month.
You need to add another axis for the bar that is a category type axis. Also its pretty critical that you have "offset: true" on that axis as well. Otherwise it will not center.
In the code below I named that category "bar" and the existing one "line"
I also created a fiddle: https://jsfiddle.net/jyf8ax3e/
var myChart = new Chart(ctx, {
type: "bar",
data: {
labels: ["2017-08", "2017-09", "2017-10", "2017-11"],
datasets: [
{
barPercentage: .7,
xAxisID: "bar",
label: "sales",
data: monthlyTotal,
backgroundColor: "green",
borderColor: "black",
borderWidth: 1,
width: 55,
order: 2,
},
{
label: "stock",
type: "line",
data: dailyStock,
backgroundColor: "orange",
borderColor: "orange",
fill: false,
order: 1,
},
],
},
options: {
scales: {
xAxes: [
{
id: "line",
type: "time",
time: {
unit: "month",
displayFormats: {
month: "MMM",
},
},
distribution: "linear",
},
{
id: "bar",
offset: true,
type: "category",
distribution: "series",
}
],
yAxes: [
{
ticks: {
beginAtZero: true,
},
},
],
},
},
});

How to pass data in Laravel with Chart.js

I want to display total of men and woman from learnings table in chart using Chartjs in Laravel.
My controller
public function index()
{
$men_learning = DB::table('learnings')->where('active', 1)->whereYear('created_at', $year)->sum('men');
$women_learning = DB::table('learnings')->where('active', 1)->whereYear('created_at', $year)->sum('women');
$learning = $men_learning + $women_learning ;
return view('home', compact('learning'));
}
My script in blade view.
<script>
var ctx = document.getElementById('myChart').getContext('2d');
var myChart = new Chart(ctx, {
type: 'bar',
data: {
labels: ['total'],
datasets: [{
label: '# of Votes',
data: [12],
backgroundColor: [
'rgba(255, 99, 132, 0.2)',
],
borderColor: [
'rgba(255, 99, 132, 1)',
],
borderWidth: 1
}]
},
options: {
scales: {
yAxes: [{
ticks: {
beginAtZero: true
}
}]
}
}
});
</script>
How can I propagate loaded statistic from my script to the chart?
public function index()
{
$men_learning = DB::table('learnings')->where('active', 1)->whereYear('created_at', $year)->sum('men');
$women_learning = DB::table('learnings')->where('active', 1)->whereYear('created_at', $year)->sum('women');
return view('home', compact('men_learning', 'women_learning'));
}
<script type="text/javascript">
$(function(){
var ctx = document.getElementById("myChart").getContext('2d');
var myChart = new Chart(ctx, {
type: 'bar',
data: {
labels: ['Men', 'Women'],
datasets: [{
label: 'Men',
data: [{!!$men_learning!!}],
borderWidth: 2,
backgroundColor: 'rgba(40,167,69,1)',
borderWidth: 0,
borderColor: 'transparent',
pointBorderWidth: 0 ,
pointRadius: 3.5,
pointBackgroundColor: 'transparent',
pointHoverBackgroundColor: 'rgba(254,86,83,.8)',
},
{
label: 'Women',
data: [{!!$women_learning!!}],
borderWidth: 2,
backgroundColor: 'rgba(220,53,69,.8)',
borderWidth: 0,
borderColor: 'transparent',
pointBorderWidth: 0,
pointRadius: 3.5,
pointBackgroundColor: 'transparent',
pointHoverBackgroundColor: 'rgba(63,82,227,.8)',
}]
},
options: {
legend: {
display: false
},
scales: {
yAxes: [{
gridLines: {
display: true,
drawBorder: false,
color: '#f2f2f2',
},
ticks: {
beginAtZero: true,
stepSize: 100,
callback: function(value, index, values) {
return value;
}
}
}],
xAxes: [{
gridLines: {
display: false,
tickMarkLength: 15,
}
}]
},
}
});
});
</script>

canvasJS x axis change between different screen

I use canvasJS to paint chart,but when the page change different window, the X axis will show different. when page open in little window show right like this enter image description here,but when page show big window show wrong like thisenter image description here
var chart = new CanvasJS.Chart("chartContainer", {
zoomEnabled: false,
animationEnabled: false,
title: {
text: "BJS Site Record Item QTY"
},
axisY2: {
valueFormatString: "0",
maximum: 50,
interval: 5,
interlacedColor: "#F5F5F5",
gridColor: "#D7D7D7",
tickColor: "#D7D7D7"
},
axisX:{
//title: "BJS Site Record Item QTY",
interval: 1
},
theme: "theme2",
toolTip: {
shared: true
},
legend: {
verticalAlign: "bottom",
horizontalAlign: "center",
fontSize: 15,
fontFamily: "Lucida Sans Unicode"
},
data: [
{
type: "line",
lineThickness: 3,
axisYType: "secondary",
showInLegend: true,
name: "BJSC",
dataPoints: [
{ x: new Date(2016,11,08), y:11 },
{ x: new Date(2016,11,09), y:0 },
{ x: new Date(2016,11,10), y:0 },
{ x: new Date(2016,11,11), y:0 },
{ x: new Date(2016,11,12), y:0 },
{ x: new Date(2016,11,13), y:0 },
{ x: new Date(2016,11,14), y:0 },
]
},
],
legend: {
cursor: "pointer",
itemclick: function (e) {
if (typeof (e.dataSeries.visible) === "undefined" || e.dataSeries.visible) {
e.dataSeries.visible = false;
}
else {
e.dataSeries.visible = true;
}
chart.render();
}
}
});
chart.render();
}
</script>
Scott,
intervalType defaults to “number” when you set the interval. If you prefer interval to be 1 day, set intervalType to "day" along with setting interval to 1.
Check this code.
var chart = new CanvasJS.Chart("chartContainer", {
zoomEnabled: false,
animationEnabled: false,
title: {
text: "BJS Site Record Item QTY"
},
axisY2: {
valueFormatString: "0",
maximum: 50,
interval: 5,
interlacedColor: "#F5F5F5",
gridColor: "#D7D7D7",
tickColor: "#D7D7D7"
},
axisX: {
//title: "BJS Site Record Item QTY",
interval: 1,
intervalType: "day"
},
theme: "theme2",
toolTip: {
shared: true
},
legend: {
verticalAlign: "bottom",
horizontalAlign: "center",
fontSize: 15,
fontFamily: "Lucida Sans Unicode"
},
data: [
{
type: "line",
lineThickness: 3,
axisYType: "secondary",
showInLegend: true,
name: "BJSC",
dataPoints: [
{ x: new Date(2016, 11, 08), y: 11 },
{ x: new Date(2016, 11, 09), y: 0 },
{ x: new Date(2016, 11, 10), y: 0 },
{ x: new Date(2016, 11, 11), y: 0 },
{ x: new Date(2016, 11, 12), y: 0 },
{ x: new Date(2016, 11, 13), y: 0 },
{ x: new Date(2016, 11, 14), y: 0 }
]
},
],
legend: {
cursor: "pointer",
itemclick: function(e) {
if (typeof(e.dataSeries.visible) === "undefined" || e.dataSeries.visible) {
e.dataSeries.visible = false;
} else {
e.dataSeries.visible = true;
}
chart.render();
}
}
});
chart.render();
<script type="text/javascript" src="http://canvasjs.com/assets/script/canvasjs.min.js"></script>
<div id="chartContainer" style="height: 250px; width: 100%;"></div>

Resources