Plot two lines on same month with different dates with Base-unit :month - kendo-ui

I am developing a chart on Kendo-UI, where we need to plot a vertical line w.r.t dates available on the x-axis. The challenge, that I am facing is my x-axis contains BaseUnit: months. when I am plotting bands w.r.t two different dates in the same month, the system generates vertical line but captures a complete month section rather than plotting two different lines in the same month.
Sample Code:
var DateRange = [];
var PlotData = [];
var AllData = [];
function BindDates() {
for (var startmonth = 01; startmonth <= 12; startmonth++) {
for (var startday = 01; startday <= 30; startday++) {
DateRange.push(new Date("2019/" + startmonth + "/" + startday));
AllData.push(Math.floor((Math.random() * startday) * new Date().getMilliseconds()));
}
for (var Initial = 1; Initial <= 3; Initial++) {
var data = null;
if (Initial == 1) {
data = { from: new Date("2019/02/03"), to: new Date("2019/02/03"), color: "red", width: 0.1 };
}
else if (Initial == 2) {
data = { from: new Date("2019/05/03"), to: new Date("2019/05/03"), color: "green", width: 0.1 };
}
else if (Initial == 3) {
data = { from: new Date("2019/06/03"), to: new Date("2019/06/03"), color: "black", width: 0.1 };
}
PlotData.push(data);
}
}
createChart(DateRange, AllData, PlotData);
}
function createChart(datesss, alldata, PlotData) {
$("#chart").kendoChart({
title: {
text: "Chart Title"
},
legend: {
position: "bottom"
},
seriesDefaults: {
type: "area",
area: {
line: {
style: "smooth"
}
}
},
series: [
{
name: "Late",
color: "orange",
data: alldata
}, {
type: "line",
dashType: "dashDot",
name: "Est DT",
color: "grey",
data: alldata
},
{
name: "On time",
color: "blue",
data: alldata
}],
valueAxis: {
labels: {
format: "{0}"
},
line: {
visible: false
},
axisCrossingValue: -10
},
categoryAxis: {
type: "date",
categories: datesss,
baseUnit: "months",
labels: {
dateFormats: {
months: "MMM-yy"
}
},
majorGridLines: {
visible: false
},
labels: {
rotation: "auto",
},
plotBands: PlotData
},
tooltip: {
visible: true,
format: "{0}%",
template: "#= series.name #: #= value #"
}
});
}
BindDates();
$(document).ready(function () {
BindDates();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://kendo.cdn.telerik.com/2019.3.1023/js/kendo.all.min.js"></script>
<div id='chart'></div>

Related

How to sort time column in jsgrid?

We are binding a table using jqgrid. We have the first column start as a time column with a 12-hour format. We are facing an issue with sorting this data. The data is sorted correctly but it is not taking am/pm into consideration. Below is our code for binding the jqgrid:
var newFieldsArray =
[
{ name: "ID", title: "ID", type: "number", width: "50px", visible: false },
{
name: "TimeStart", title: "Start", type: "customTime", width: "100px", validate: "required",
sorttype: "date",
formatter : {
date : {
AmPm : ["am","pm","AM","PM"],
}
},
// datefmt: "m/d/Y h:i A",
//sorttype: 'datetime', formatter: 'date', formatoptions: {newformat: 'd/m/y', srcformat: 'Y-m-d H:i:s'},
insertTemplate: function () {
var $result = jsGrid.fields.customTime.prototype.insertTemplate.call(this); // original input
$result.val(varendTime);
return $result;
},
itemTemplate: function (value, item) {
return "<b style='display:none'>" + Date.parse(item.StartDate) + "</b><span>" + (item.TimeStart) + "</span>";
}
},
{
name: "TimeEnd", title: "End", type: "customTime", width: "100px", validate: "required",sorttype: "date", datefmt: "h:i"
},
{ name: "TimeTotal", title: "Time", type: "text", width: "50px", readOnly: true },
{
name: "CoilPO", title: "Coil PO", type: "text", width: "50px", validate: "required",
insertTemplate: function () {
var $result = jsGrid.fields.text.prototype.insertTemplate.call(this); // original input
$result.val(varlot);
return $result;
}
},
{ name: "Joints", title: "Joints", type: "integer", width: "60px" },
{ name: "CommercialGrade", title: "Commercial Grade", type: "integer", width: "80px" },
{ name: "QAHold", title: "QA Hold", type: "integer", width: "60px" },
{ name: "Rejected", title: "Reject", type: "integer", width: "60px" },
{ name: "ActionTaken", title: "Reason of Delay / Action Taken", type: "text", width: "120px" },
{
name: "ClassId", title: "Class",
type: "select", items: classDataArr,//classData.filter(function(n){return classdt.indexOf(n.Id) != -1 }),//classData,
valueField: "Id", textField: "Title",
insertTemplate: function () {
debugger;
var taxCategoryField = this._grid.fields[12];
var $insertControl = jsGrid.fields.select.prototype.insertTemplate.call(this);
var classId = 0;
var taxCategory = $.grep(voiceData, function (team) {
return (team.ClassId) === classId && (team.StationId) == parseInt($('#ddlEquipmentName').val());
});
taxCategoryField.items = taxCategory;
$(".tax-insert").empty().append(taxCategoryField.insertTemplate());
$insertControl.on("change", function () {
debugger;
var classId = parseInt($(this).val());
var taxCategory = $.grep(voiceData, function (team) {
return (team.ClassId) === classId && (team.StationId) == parseInt($('#ddlEquipmentName').val());
});
taxCategoryField.items = taxCategory;
$(".tax-insert").empty().append(taxCategoryField.insertTemplate());
});
return $insertControl;
},
editTemplate: function (value) {
var taxCategoryField = this._grid.fields[12];
var $editControl = jsGrid.fields.select.prototype.editTemplate.call(this, value);
var changeCountry = function () {
var classId = parseInt($editControl.val());
var taxCategory = $.grep(voiceData, function (team) {
return (team.ClassId) === classId && (team.StationId) == parseInt($('#ddlEquipmentName').val());
});
taxCategoryField.items = taxCategory;
$(".tax-edit").empty().append(taxCategoryField.editTemplate());
};
debugger;
$editControl.on("change", changeCountry);
changeCountry();
return $editControl;
}
},
{
name: "VoiceId", title: "Voice", type: "select", items: voiceData,
valueField: "Id", textField: "Title", width: "120px", validate: "required",
insertcss: "tax-insert",
editcss: "tax-edit",
itemTemplate: function (teamId) {
var t = $.grep(voiceData, function (team) { return team.Id === teamId; })[0].Title;
return t;
},
},
{ name: "Remarks", title: "Remarks", type: "text", width: "110px" },
{ name: "control", type: "control" }
];
hoursGrid.jsGrid("option", "fields", newFieldsArray);
Below is two screenshots of data that appear when we sort:
Can someone tell me what we are doing wrong?
You're mixing up jsGrid and jqGrid. The way to achieve it in jsGrid is using the built-in sorter jsGrid.sortStrategies.date, I added an example below.
As commented by #Tomy Tomov (the creator of jqGrid), you're using jsGrid, not jqGrid. This is evident both by your code and by the UI in the screenshot.
Specifically, you took the date sorter of jqGrid and used it in your jsGrid code, but (of course) it's not supported there. You can go ahead and look in jsGrid source for AmPm which you used - and see it's not there.
So how to do it in jsGrid?
Just pass the built-in sorter jsGrid.sortStrategies.date to the sorter property. However, it does require Date objects, so if you only got time strings, you'll have to convert those to dates.
Below is a quick demo (jsfiddle), click the date column title to sort:
Note that getData gets a function parameter that is responsible to get all data as Date objects, and that the value of isUTC depends on whether you actually use it
$(document).ready(function () {
const dataFunc = getDataTimes;
$("#jsGrid").jsGrid({
width: "100%",
data: getData(dataFunc),
sorting: true,
fields: [{
name: "name",
type: "text",
width: 50
}, {
name: "date",
type: "date",
width: 50,
sorter: jsGrid.sortStrategies.date,
cellRenderer: (value, item) => {
const withYear = false;
const isUTC = dataFunc == getDataTimes;
return renderDateTime(value, item, withYear, isUTC);
}
}
]
});
});
function getData(getDates) {
const data = [
{name: "a"}, {name: "b"}, {name: "c"},
{name: "d"}, {name: "e"}, {name: "f"},
];
const dates = getDates();
for (let i = 0; i < dates.length; i++) {
data[i].date = dates[i];
}
return data;
}
function getDataDates() {
const date1 = new Date(2022, 10, 1, 4, 50);
const date2 = new Date(2022, 10, 1, 8, 50);
const date3 = new Date(2022, 10, 1, 15, 50);
const date4 = new Date(2021, 10, 1, 4, 50);
const date5 = new Date(2021, 10, 1, 8, 50);
const date6 = new Date(2021, 10, 1, 15, 50);
return [date1, date2, date3, date4, date5, date6];
}
function getDataTimes() {
const time1 = "3:50 AM";
const time2 = "8:50 AM";
const time3 = "4:50 AM";
const time4 = "3:50 PM";
const time5 = "8:50 PM";
const time6 = "4:50 PM";
const times = [time1, time2, time3, time4, time5, time6];
return times.map(t => convertTime12to24(t));
}
function convertTime12to24(time12h) {
const [time, modifier] = time12h.split(' ');
let [hours, minutes] = time.split(':');
if (modifier === 'PM') {
hours = parseInt(hours, 10) + 12;
}
return new Date(Date.UTC(2022,0,1,hours, minutes));
}
function renderDateTime(value, row, withYear, isUTC) {
return `<td>${getDateTimeAsString(value, withYear, isUTC)}</td>`;
}
function getDateTimeAsString(date, withYear, isUTC) {
var options = {
hour: 'numeric',
minute: 'numeric',
hour12: true
};
if (withYear) {
options.withYear = 'numeric';
}
if (isUTC) {
options.timeZone = 'UTC';
}
return date.toLocaleString('en-US', options);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jsgrid/1.5.3/jsgrid.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.13.2/jquery-ui.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/jsgrid/1.5.3/jsgrid-theme.min.css" rel="stylesheet">
<link href="https://cdnjs.cloudflare.com/ajax/libs/jsgrid/1.5.3/jsgrid.min.css" rel="stylesheet">
<div id="jsGrid" class="jsgrid"></div>
Let me give it a try, we have 2 options to perform Sorting operation in JsGrid:
1.Custom Field (Topic Name you can refer below link)
Reference Link :http://js-grid.com/docs/#grid-fields
In this, you can define custom property in your config and extend it.
You can use sorter property and call your user defined function werein you can logic to sort date with time stamps directly.
2.Sorting Strategies (Topic Name you can refer below link)
Reference Link :http://js-grid.com/docs/#grid-fields
In this, you can create your custom objects and then apply sorting strategies of date directly on to the object to perform sorting operation as per your logic.

c3.js reduce width of x-axis

is there a way to reduce the width of x-axis (see picture) in c3? Even if I tried to set "stroke-width" attribute to the "<"path">" tag with different values - it didn't make any visual changes. Thank you for your advices in advance.
Picture
var chart = c3.generate({
bindto: '#' + chartId,
data: {
columns: columns,
type: 'bar',
labels: true
},
interaction: {
enabled: false
},
tooltip: {
show: false
},
color: {
pattern: colorPattern
},
bar: {
width: { ratio: 0.7 },
space: 0.25
},
size: settings.ChartSizes.BarChart,
legend: {
position: 'right',
grouped: true,
item: {
onclick: function (d) {
counter++;
if (counter === 1) {
chart.hide();
chart.show(d);
} else {
chart.show();
counter = 0;
}
}
}
},
axis: {
x: {
type: 'category',
categories: categories,
show: showAxe
},
y: {
show: false
}
}
});
This is a common issue, caused by you not picking up the c3.css file - see https://github.com/c3js/c3/issues/1962
If you can fix that, the problem goes away

Chartjs2 Legend Not working

I'm trying to plot a lineal graphic that gets data from ajax using Chartjs 2.5.
This is the main function for this procedure. The main problem is that the legend doesn't appear.
function initDigitalValueChart(divName, ids) {
if ($(divName)) {
/*for (var j=0; j<ids.length; j++) {
console.log(j);
datasetValue[j] = {
fillColor: 'rgba(220,220,220,0.5)',
strokeColor :'rgba(220,220,220,1)',
title :'2013',
data : [Math.round(Math.random() * 1),Math.round(Math.random() * 1)]
}
}*/
var datasetValue = [];
var calls = [];
for (var j = 0; j < ids.length; j++) {
var labels = []
URL = "*****" + ids[j];
calls.push($.getJSON(URL, function(response) {
var values = []
if (response != null) {
$.each(response, function(index, data) {
labels.push(data["timestamp"]);
values.push(data["value"]);
title = data["sensorName"]
});
datasetValue.push({
label: title,
lineTension: 0,
borderColor: "rgba(" + Math.floor(Math.random() * 255) + ", " + Math.floor(Math.random() * 255) + ", " + Math.floor(Math.random() * 255) + ", 0.70)",
backgroundColor: "transparent",
data: values,
radius: 0,
pointHitRadius: 0,
steppedLine: true,
});
}
}))
}
$.when.apply($, calls).then(function() {
var ctx = document.getElementById('digital').getContext("2d");
var lineChart = new Chart(ctx, {
type: 'line',
data: {
labels: labels,
datasets: datasetValue
},
options: {
legend: {
display: true,
labels: {
fontColor: "white",
fontSize: 18
}
},
scales: {
xAxes: [{
display: true,
scaleLabel: {
display: true,
labelString: 'Data Hora'
}
}],
yAxes: [{
display: true,
scaleLabel: {
display: true,
labelString: 'Valor'
}
}]
}
}
});
//document.getElementById('digital-legend').innerHTML = lineChart.generateLegend();
});
}
}
I tried to add the position: 'top' option but in this case the console returns
Uncaught TypeError: Cannot read property 'call' of undefined
Has anyone else had problems with this?

How to get the datasource information from Kendo UI dragend event?

This is the code for the line chart which has drag function to highlight some data. I would like to get the datasource information in the dragEnd event,currently I am just getting screenX and screenY values.
function createChart(data) {
$("#TimeSeriesPlot").kendoChart({
title: {
text: series_name.toUpperCase()
},
dataSource :{
data:data.timeseries,
},
series: [{
type: "line",
field:"v",
categoryField:"ts",
}],
valueAxis: {
labels: {
format: "{0}"
},title:{
text: "value"
},
line: {
visible: false
},
},
categoryAxis: {
labels: {
type: "date",
},
tooltip: {
visible: true,
// shared:true,
template: "${category} - ${value}"
},
plotAreaClick: onPlotAreaClick,
seriesClick:onSeriesClick ,
dragStart:onDragStart ,
drag:onDrag,
dragEnd:onDragEnd
});
}
}
function onSeriesHover(e) {
console.log(kendo.format("Series hover :: {0} ({1}): {2}",
e.series.name, e.category, e.value));
}
function onSeriesClick(e){
// console.log(selected_anamolies);
// console.log(e.category);
selected_anamolies.push("ts",e.category);
selected_anamolies.push("v",e.value);
}
function onDragStart(e){
// console.log("dragstart"+e.axisRanges.ts);
// console.log("dragstart"+e.sender._highlight._points[0].value);
// console.log("dragstart"+e.sender._highlight._points[0].category);
}
function onDrag(e){
var Rect = kendo.geometry.Rect;
var draw = kendo.drawing;
prevloc=e.originalEvent.x.startLocation;
currentloc=e.originalEvent.x.location;
var rect=new Rect([prevloc,50],[currentloc-prevloc,150]);
var path = draw.Path.fromRect(rect,{ stroke: null,fill:{color:"#d3f1fb",opacity:0.2}});
var chart = e.sender;
// var surface = draw.Surface.create($("#surface"));
chart.surface.draw(path);
//
}
function onDragEnd(e){
console.log(dragEnd)
}

How to plot 500 points in a second in highchart?

We are supposed to plot 500 points every second from ajax request which we get it from WCF service(hosted in amazon cloud).
We are using highchart, but its very slow.
Is there any solution ? or any other graph control which we can use it in our case so that performnace is efficient
var chart = new Highcharts.Chart({
chart: {
type: 'spline',
animation: false,//Highcharts.svg, // don't animate in old IE
marginRight: 10,
renderTo: 'Chart',
events: {
load: function () {
}
}
},
title: {
text: 'Data'
},
xAxis: {
type: 'datetime',
tickPixelInterval: 150,
max: ((new Date()).getTime()) + 50 * 10000
},
yAxis: {
title: {
text: 'Data',
min: 50,
max: 500
},
plotLines: [{
value: 0,
width: 1,
color: '#FFFF00'
}]
},
plotOptions: {
line: {
marker: {
enabled: false
}
}
},
tooltip: {
},
legend: {
enabled: false
},
exporting: {
enabled: false
},
plotOptions: {
series: {
marker: {
enabled: false
}
}
},
series: [{
name: 'Chart',
color: '#335de8',
//data: []
data: (function () {
//generate an array of random data
var data = [];
var data = [],
time = (new Date()).getTime(), i;
for (i = 1; i <= 0; i++) {
data.push({
x: time + i * 1000,
y: null
});
}
return data;
})()
}]
});
chart.yAxis[0].setExtremes(-200, 500);
UpdateChart();
function UpdateChart() {
var Chrt = chart.series[0];
setInterval(function () {
$.ajax({
url: 'getChartData/',
cache: false,
type: "POST",
success: function (result) {
for (var tmpJ = 0; tmpJ < result.length; tmpJ++) {
Chrt.addPoint([(new Date()).getTime(), eval(result[tmpJ])], true, false);
Chrt.redraw(false);
}
});
}, 1000);
}
Try to replace this line
Chrt.addPoint([(new Date()).getTime(), eval(result[tmpJ])], true, false);
with
if(tmpJ==result.length-1){
Chrt.addPoint([(new Date()).getTime(), eval(result[tmpJ])], false, false);
} else {
Chrt.addPoint([(new Date()).getTime(), eval(result[tmpJ])], true, false);
}

Resources