What is the correct format for time data in chartjs? - time

My chart is plotting x-axis points from Jan 1 1970. My js is below. Is the format of my x-coordinates what is causing the problem, and if so, how can I get these dates right?
var chart = new Chart(document.getElementById('myChart'), {
type: 'line',
data: {
datasets: [{
data: [{x:15-04-2018,y:10},{x:16-04-2018,y:20},{x:17-04-2018,y:30}],
borderColor: '#3e95cd',
fill: false
}]},
options: {
scales: {
xAxes: [{
type: 'time',
unit: 'day' ,
distribution: 'linear',
ticks: { source: 'data' },
time: { displayFormats: { day: 'MMM DD' } }
}]
},
title: {
display: true,
text: 'Student Assessment Cluster Scores'
},
} });

The date values must be entered as a javascript Date object. Just like the documentation says,
data: [{
x: new Date(),
y: 1
}, {
t: new Date(),
y: 10
}]
So in my question, the dates could be represented by:
data: [
{x:new date(15-04-2018),y:10},
{x:new date(16-04-2018),y:20},
{x:new date(17-04-2018),y:30}
]

Related

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 configure linear labels in Time Cartesian Chartjs?

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>

include two series from database in a highchart chart

I would like to include a series to my existing chart.
daytime = new Highcharts.Chart({
chart: {
renderTo: 'daytime_div',
defaultSeriesType: 'areaspline',
events: {
load: getData()
}
},
plotOptions: {
series: {
fillOpacity: 0.1,
lineWidth: 4,
marker: {
radius: 5,
lineWidth: 1,
lineColor: "#FFFFFF"
}
}
},
tooltip: {
formatter: function () {
var s = [];
$.each(this.points, function (i, point) {
s.push('<span style="font-size:10px;">' + point.key + '</span><br/><strong>' + point.series.name + '</strong> : ' + point.y + '</span>');
});
return s.join('<br/>');
},
shared: true,
useHTML: true
},
credits: false,
title: false,
exporting: false,
legend: {
itemDistance: 50,
itemStyle: {
color: '#333'
}
},
xAxis: {
labels: {
staggerLines: 2
}
},
yAxis: {
gridLineColor: "#e7e7e7",
title: {
text: ''
},
labels: {
x: 15,
y: 15,
style: {
color: "#999999",
fontSize: "10px"
}
},
},
series: [{
name: 'Daily',
color: "#b18eda",
data: ddata
}]
});
function getData() {
$.ajax({
url: '...',
type: "POST",
contentType: "application/json; charset=utf-8",
data: data,
success: function (f) {
var categories = [];
var series_data = [];
$.each(f.d, function (i, e) {
categories.push(e.hour);
series_data.push(parseInt(e.numa));
});
daytime.xAxis[0].setCategories(categories);
daytime.series[0].setData(series_data);
},
cache: false
});
}
The data I get from my database looks like this:
hour, numa
12 AM 1
1 AM 0
2 AM 0
3 AM 0
4 AM 0
This shows one line in the chart which is fine. I would like to add a second line that will come from a different query. The second line data will look like:
hour, numa
12 AM 0
1 AM 12
2 AM 3
3 AM 2
4 AM 2
Does anyone knows how could I include this into my second series? I have seen the sample in high charts on how to add more series. Static is pretty simple but getting the data dynamically make it more complicated to figure it out.
I am trying to find a way to add 2 series to my getData() function. Any idea will be appreciate it thanks.
It is explained clearly in the fiddle of the document which you shared on how to add multiple series.
series: [{
name: 'Tokyo',
data: [7.0, 6.9, 9.5, 14.5, 18.2, 21.5, 25.2, 26.5, 23.3, 18.3, 13.9, 9.6]
}, {
name: 'New York',
data: [-0.2, 0.8, 5.7, 11.3, 17.0, 22.0, 24.8, 24.1, 20.1, 14.1, 8.6, 2.5]
}, {
name: 'Berlin',
data: [-0.9, 0.6, 3.5, 8.4, 13.5, 17.0, 18.6, 17.9, 14.3, 9.0, 3.9, 1.0]
}, {
name: 'London',
data: [3.9, 4.2, 5.7, 8.5, 11.9, 15.2, 17.0, 16.6, 14.2, 10.3, 6.6, 4.8]
}]
You can pass multiple series in array and the chart can be generated.
EDIT-1
If data from different series use this fiddle.
var myComments=["First input","second comment","another comment","last comment"]
var dataValues = [29.9, 71.5, 194.1, 129.2];
var dataValues2 = [194.1, 95.6, 194.1, 29.9];
var categories = ['Jan', 'Feb', 'Mar', 'Apr'];
var n=['tooltip1','tooltip2','tooltip3','tooltip4'];
$(function () {
$('#container').highcharts({
chart: {},
tooltip: {
formatter: function () {
var serieI = this.series.index;
var index = categories.indexOf(this.x);
var comment = myComments[index];
return '-->'+comment;
}
},
xAxis: {
categories: categories
},
series: [{
data: dataValues
}, {
data: dataValues2
}]
});
});
which results in the below graph
Well you can use $.when() and load there all your ajax and in $.then() initialise chart. Second solution is prepare your query to database and return all data in single json.

How to process json object in highchart

I receive an array json object. And now I don't know how I can process it in javascript code to series section data. I use this example of highchart column-rotated-labels. In this object has two columns AVG and other title, and length of this object might 20.
This is my codes:
$('#showresult').click(function() {
$.ajax({
url : "../../coursestatus",
type : "get",
data : {
major : $('#get').val(),
year : $('#yearlist').val(),
semester : $('#semester').val()
},
success : function(data) {
alert(data.length);
$(function () {
$('#container').highcharts({
chart: { type: 'column'
},
title: { text: 'World\'s largest cities per 2014' },
xAxis: {
type: 'category',
labels: {
rotation: -45,
}
},
yAxis: { min: 0,
title: {
text: 'Population (millions)'
} },
legend: { enabled: false },
tooltip: { pointFormat: 'Population in 2008: <b>{point.y:.1f} millions</b>' },
series: [{ // I don't know how I can process data object to set that's elements to this
name: 'Population',
data: [
JSON.parse("[" + data + "]")
],
dataLabels: { enabled: true,
rotation: -90,
color: '#FFFFFF',
align: 'right',
x: 4,
y: 10,
style: { fontSize: '13px',
fontFamily: 'Verdana, sans-serif', textShadow: '0 0 3px black'
}
}
}]
});
});
And this object include this elements:
title columns includes course name and avg columns includes mark for that course.
And this is data is in data object:
[{"title":"Math","avg":20},{"title":"Network","avg":18},{"title":"Operating system","avg":16}]
And above data is has 3 length and it is simple, in fact this object maybe that's length is >10.
Thank u!
I founded similar problem in this page and I solved my problem.
Populate Highcharts with JSON data using jQuery

How to make bar thicker in Kendo UI chart?

My chart has a calories vs time data. The calories has values every 15 min. I want to make the bars closer. I am posting a sample of the data and also a link to the jsFiddle. Also, is it possible to have the entire 24 hours displayed on the chart and show only the ones which are having values...
var data= [{"IntraDayFifteenMinuteActivityKey":443124,"id":"abcd","datetimedata":"7/20/2014 4:15:00 AM","caloriesOut":"17","distance":"0","elevation":"0","floors":"0","steps":"0","createddate":"7/20/2014 12:00:00 AM","distanceunit":"Km"},
{"IntraDayFifteenMinuteActivityKey":443125,"id":"abcd","datetimedata":"7/20/2014 4:30:00 AM","caloriesOut":"20","distance":"0","elevation":"0","floors":"0","steps":"0","createddate":"7/20/2014 12:00:00 AM","distanceunit":"Km"},
{"IntraDayFifteenMinuteActivityKey":443126,"id":"abcd","datetimedata":"7/20/2014 4:45:00 AM","caloriesOut":"17","distance":"0","elevation":"0","floors":"0","steps":"0","createddate":"7/20/2014 12:00:00 AM","distanceunit":"Km"},
{"IntraDayFifteenMinuteActivityKey":443127,"id":"abcd","datetimedata":"7/20/2014 5:00:00 AM","caloriesOut":"17","distance":"0","elevation":"0","floors":"0","steps":"0","createddate":"7/20/2014 12:00:00 AM","distanceunit":"Km"},
{"IntraDayFifteenMinuteActivityKey":443128,"id":"abcd","datetimedata":"7/20/2014 5:15:00 AM","caloriesOut":"17","distance":"0.00442800018936396","elevation":"0","floors":"0","steps":"6","createddate":"7/20/2014 12:00:00 AM","distanceunit":"Km"},
{"IntraDayFifteenMinuteActivityKey":443129,"id":"abcd","datetimedata":"7/20/2014 5:30:00 AM","caloriesOut":"17","distance":"0","elevation":"0","floors":"0","steps":"0","createddate":"7/20/2014 12:00:00 AM","distanceunit":"Km"}]
$("#IntraDayDataChart").kendoChart({
dataSource: data,
seriesColors: [color],
chartArea: {
background: ""
},
title: {
text: "Intraday Data",
font: "14px Arial,Helvetica,sans-serif bold"
},
legend: {
visible: false,
},
chartArea: {
background: ""
},
seriesDefaults: {
type: "column",
overlay: {
gradient: "none"
},
gap: .1
},
series: [{
name: type,
field: type
}],
categoryAxis: {
field: "datetimedata",
majorGridLines: {
visible: false
},
majorTicks: {
visible:false
},
type: "date",
baseUnit: "minutes",
labels: {
dateFormats: {
minutes: "h tt"
},
step:180
}
},
valueAxis: {
majorGridLines: {
visible: true
},
majorTicks: {
visible:false
},
labels: {
visible: false
},
title: {
text: type,
font: "14px Arial,Helvetica,sans-serif"
},
visible: false
},
tooltip: {
visible: true,
template: '#=kendo.toString(new Date(dataItem.datetimedata),"g")# <br /> #=kendo.toString(Number(dataItem.' + type + '),"n2")# ' + type
}
});
}
}
Link to Fiddle
To make your chart lines thicker you need to decrease the gap in the series.
$("#chart").kendoChart({
series: [ {
gap: 0
}]
});
Here is the API reference
http://docs.telerik.com/kendo-ui/api/dataviz/chart#configuration-series.gap
They have a tutorial of how to do this on the fly as well.
http://demos.telerik.com/kendo-ui/bar-charts/gap-spacing
For only displaying the time with data you would have to define the CategoryAxis as type 'category' instead of type 'date'. When you define it as a date kendo will fill in all the missing data points with blank so that it looks right. For this to work you may have to convert you dates to something that will order right as a category.
You instead could have kendo auto aggregate your data such that it will chunk together time. You can set this by setting the baseUnit in the CaregoryAxis to 'fit'
$("#chart").kendoChart({
categoryAxis: {
baseUnit: "fit"
}
});

Resources