Kendo Change SeriesDefault Chart Type Dynamically - dynamic

The Code works But I wanna Change Chart Type Dynamically. I tried Change Chart Type in function WeightLine However It does not work. It changes SeriesDefault type , I see new chart type in alert but does not draw new chart type.
var mydata=[{"date":"2013-03-06","data":2916,"name":"weight"},{"date":"2013-03-05","data":3708,"name":"weight"}];
function getFilter(xMin, xMax) {
return [{
field: "date",
operator: "gt",
value: xMin
}, {
field: "date",
operator: "lt",
value: xMax
}];
}
$("#line_chart_weight").kendoChart({
title: {
text: "weight"
},
dataSource:{
data: mydata,
group: {
field: "name"
},
sort: {
field: "date",
dir: "asc"
},
schema: {
model: {
fields: {
date: {
type: "date"
}
}
}
}
},
seriesDefaults: {
type: "scatterLine"
},
series: [{
xField:"date",
yField: "data"
}],
yAxis: {
labels: {
format: "{0}"
},
title: {
text: "KG",
padding: {
left: 20
}}
}, xAxis: {
labels:
{
rotation: -90,
format:"dd-MM-yyyy"
},
title: {
text: "Date",
padding: {
top: 20
}},
type:"date",
name:"CategoryAxis"
},
tooltip: {
visible: true,
format:"dd-MM-yyyy",
color:"white"
},
transitions: false,
drag: onDragw,
zoom: onDragw
});
var weight=$("#line_chart_weight").data("kendoChart");
function onDragw(e) {
var ds = weight.dataSource;
var options = weight.options;
e.originalEvent.preventDefault();
var categoryRange = e.axisRanges.CategoryAxis;
if (categoryRange) {
var xMin = categoryRange.min;
var xMax = categoryRange.max;
options.categoryAxis.min = xMin;
options.categoryAxis.max = xMax;
ds.filter(getFilter(xMin, xMax));
weight.redraw();
}
}
function WeightLine(WeightTypeString){ weight.options.seriesDefaults.type=WeightTypeString;alert(weight.options.seriesDefaults.type); weight.redraw();}

it is a bit weird but i write something to solve this. both of them worked for me. You can modify them for your code.
1.
var chart = $("#chartId").data("kendoChart");
chart.setOptions({ seriesDefaults: {type : "radarColumn"} });
chart.dataSource.read();
chart.refresh();
2.
var chart = $("#chartId").data("kendoChart");
for(i = 0; i< chart.options.series.length;i++){
chart.options.series[i].type = "radarColumn";
}
chart.refresh();

Related

Chart.JS Get the Y Axis value based on the X axis value

Need some guidance. I have a chart which is displaying tide times throughout the day.
What I need to do is mark on the curve the height (Y Axis) based on the current time of day:
e.g. If the time was 14:00
Here is my code:
const chart = new Chart(this.$refs.myChart, {
type: "line",
data: {
labels,
datasets: [
{
data,
tension: 0.5,
backgroundColor: "rgb(31,89,112,0.5)",
borderColor: "rgb(31,89,112,1)",
fill: {
target: "origin",
},
},
],
},
options: {
interaction: {
mode: "point",
},
hover: {
mode: "point",
},
onHover: (e) => {
const canvasPosition = getRelativePosition(e, chart);
// Substitute the appropriate scale IDs
const dataX = chart.scales.xAxis.getValueForPixel(
canvasPosition.x
);
const dataY = chart.scales.yAxis.getValueForPixel(
canvasPosition.y
);
// console.log(dataY);
},
plugins: {
tooltip: {
enabled: true,
callbacks: {
label: function(context) {
var label = context.dataset.label || "";
if (label) {
label += ": ";
}
if (context.parsed.y !== null) {
label += context.parsed.y + "m";
}
return label;
},
},
},
legend: {
display: false,
},
},
scales: {
xAxis: {
type: "time",
min: new Date(date), // Should calculate this dynamic, not best way but can use: new Date().setHours(0,0,0,0)
max: new Date(date + (86400000 - 1000)),
time: {
unit: "hour",
stepSize: 2,
displayFormats: {
hour: "HH:mm",
},
// minUnit: moment(1634860800000).format("HH:mm"),
},
ticks: {
major: true,
},
},
yAxis: {
ticks: {
callback: function(value, index, values) {
return value + "m";
},
},
},
},
},
});
Any ideas how I can achieve the red dot. I have tried addeding a second dataset however this doesnt follow the curve (As the curve is generated by tension: 0.5)?
Thanks in advance!
Edit
Here is a sample of what would be in var data and var labels
var labels = [
'2021-11-04T05:26:52.5',
'2021-11-04T11:21:06.667',
'2021-11-04T17:55:52.5',
'2021-11-04T23:47:30',
'2021-11-05T06:11:37.5'
]; // Times
var data = [
0.9,
5.3,
0.4,
5.4,
0.8
]; // Heights

Vue-Charts label numbers to the side of a bar chart

I am using a Nuxt application with vue-charts. I have a barchart that I trying to see if there is a way to callback the numbers next to the chart. Some what like this
My barchart options look like this now.
barLostDollarChartOptions: {
responsive: true,
maintainAspectRatio: false,
legend: {
display: false,
},
title: {
display: true,
text: 'Daily NP Opportunity Costs'
},
scales: {
yAxes: [{
//Sets the Max value after re-rendering chart
beforeFit: function (scale){
let maxValue = 0
if (scale.chart.config && scale.chart.config.data && scale.chart.config.data.datasets) {
scale.chart.config.data.datasets.forEach(dataset => {
if (dataset && dataset.data) {
dataset.data.forEach(value => {
if (value > maxValue) {
maxValue = value
}
})
}
})
}
// After, set max option !!!
scale.options.ticks.max = maxValue
},
// afterFit: function (scale){
// console.log('yAxes',scale)
// let arr = Object.values(scale.chart.config.data.datasets[0].data);
// let min = Math.min(...arr);
// let max = Math.max(...arr);
// maxValueArray.push(max)
// // console.log( `Min value: ${min}, max value: ${max}` );
//
// }
}
],
xAxes: [{
ticks:{
callback: function(value, index, values) {
if(parseInt(value) >= 1000){
// console.log(value.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ","))
return '$' + value.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
} else {
return '$' + value;
}
},
},
}]
}
},
But I am trying to see if there is a way that I can call back the number and render it next to the bar? any ideas?
You can use the datalabels plugin for this:
Chart.plugins.register(ChartDataLabels);
var options = {
type: 'horizontalBar',
data: {
labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
datasets: [{
label: '# of Votes',
data: [12, 19, 3, 5, 2, 3],
backgroundColor: 'orange'
}]
},
options: {
plugins: {
datalabels: {
anchor: 'end',
align: 'end',
formatter: (val) => ('$' + val)
}
}
}
}
var ctx = document.getElementById('chartJSContainer').getContext('2d');
new Chart(ctx, options);
<body>
<canvas id="chartJSContainer" width="600" height="400"></canvas>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.4/Chart.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/chartjs-plugin-datalabels/1.0.0/chartjs-plugin-datalabels.js"></script>
</body>

How to select all checkbox based on custom checkbox in filterTemplate in JsGrid

Here i am trying to check all checkbox for using custom checkbox we can see here filterTemplate section and selectAll or unselectAll these are Bold for getting my point
<script>
$(function () {
$.ajax({
type: "GET",
url: "/MerchandiseList/GetMerchant"
}).done(function (data) {
//$("#leftMenu").hide();
//reloadpage(data);
var MyDateField = function (config) {
jsGrid.Field.call(this, config);
};
MyDateField.prototype = new jsGrid.Field({
sorter: function (date1, date2) {
return new Date(date1) - new Date(date2);
},
itemTemplate: function (value) {
if (value == "")
return "";
else {
var date = new Date(value).toDateString()
//var date = new Date(value).toDateString("MM/dd/yyyy")
//return new Date(value).toDateString();
//return value;
var d = new Date(date),
month = '' + (d.getMonth() + 1),
day = '' + d.getDate(),
year = d.getFullYear();
if (month.length < 2) month = '0' + month;
if (day.length < 2) day = '0' + day;
var df = [month, day, year].join('/');
//var df = [year, month, day].join('/');
date = df;
return date;
}
},
insertTemplate: function (value) {
return this._insertPicker = $("<input>").datepicker({ defaultDate: new Date() });
},
editTemplate: function (value) {
if (value == "")
return this._editPicker = $("<input>").datepicker({ defaultDate: new Date() });
else {
return this._editPicker = $("<input>").datepicker().datepicker("setDate", new Date(value));
}
},
insertValue: function () {
if (this._insertPicker.datepicker("getDate") != null)
return this._insertPicker.datepicker("getDate"); //.toISOString("MM/dd/yyyy")
//else
// return this._insertPicker.datepicker("getDate");
},
editValue: function () {
//debugger
if (this._editPicker.datepicker("getDate") != null)
//.toISOString("MM/dd/yyyy")
return this._editPicker.datepicker("getDate");
//return this._editPicker.datepicker("getDate").toISOString();
//else
// return this._editPicker.datepicker("getDate");
}
});
jsGrid.fields.myDateField = MyDateField;
$("#jsGrid").jsGrid({
height: "50%",
width: "100%",
filtering: true,
editing: true,
editButtonTooltip: "Edit",
inserting: true,
sorting: true,
paging: true,
autoload: true,
pageButtonCount: 5,
pageSize: 15,
overflow: scroll,
confirmDeleting: true,
deleteConfirm: "Do you really want to delete the merchandise?",
//refreshtext: "Refresh",
//onRefreshed: function (args) { },
selecting: true,
controller: db,
fields: [
{
**filterTemplate**: function (_, item) { // how to get all grid items here? This return only single item but empty in Filter row.
return $("<input>").attr("type", "checkbox")
.prop("checked", $.inArray(item, selectedItems) > -1)
.on("change", function () {
$(this).is(":checked") ? selectAll(item) : unselectAll(item);
});
},
itemTemplate: function (_, item) {
return $("<input>").attr("type", "checkbox")
.prop("checked", $.inArray(item, selectedItems) > -1)
.on("change", function () {
$(this).is(":checked") ? selectItem(item) : unselectItem(item);
});
},
align: "center",
width: 50,
sorting: false,
filtering: false
},
{ type: "control" },
{
name: "Source", type: "text", width: 120, title: "Vendor"
},
{
name: "Description", type: "text", width: 210,
validate: { message: "Description is required!", validator: function (value) { return value != ""; } }
},
{
name: "ModelNumber", type: "text", width: 120, title: "Model#/Item"
},
{ name: "SKU", type: "text", width: 90 },
{ name: "SKU2", type: "text", width: 90 },
{ name: "Comments", type: "text", width: 200 },
{ name: "strReceiveDate", type: "myDateField", width: 80, align: "center", title: "Received" },
{ name: "Location", type: "select", items: data.loc, valueField: "LocationID", textField: "Description", width: 100 },
{ name: "Barcode", width: 80 },
{ name: "BarcodePrinted", type: "checkbox", title: "Barcode Printed", sorting: false },
//{ name: "strLastUpdatedDate", type: "myDateField", width: 80, title: "Last Updated" },
{ name: "strLastUsedDate", type: "myDateField", width: 80, title: "Last Updated" },
{ name: "DamageCode", type: "select", items: data.dam, valueField: "CodeID", textField: "CodeValue", title: "Damage" },
{ name: "strCreatedDate", editable: false, width: 80, title: "Created Date", type: "myDateField" },
{ name: "strShipDate", type: "myDateField", myCustomProperty: "bar", width: 80, title: "Ship Date" },
{ name: "strConsumeDate", type: "myDateField", myCustomProperty: "bar", width: 80, title: "Consume Date" },
{ name: "PendingShipment", type: "checkbox", title: "Pending", sorting: false, width: 60 },
{ name: "Donated", type: "checkbox", title: "Is Donated", sorting: false, width: 60 },
{ name: "ReturnRequested", type: "checkbox", title: "Return Requested", sorting: false },
{ name: "ReturnTo", type: "text", width: 150, title: "Return To" },
{ name: "Quantity", type: "number", width: 50, title: "Qty" },
{ name: "GroupName", type: "text", width: 150, title: "Group Name" },
{ name: "CustomerID", width: 100, title: "Customer ID" }
],
});
var selectedItems = [];
var selectItem = function (item) {
document.getElementById("hdn").value = document.getElementById("hdn").value + "," + item.Barcode;
selectedItems.push(item);
//debugger
var $grid = $("#jsGrid");
$grid.jsGrid("option", "editing", false);
$grid.jsGrid("option", "editing", true);
};
var unselectItem = function (item) {
selectedItems = $.grep(selectedItems, function (i) {
//debugger
return i !== item;
});
var value = document.getElementById("hdn").value;
value = value.replace(item.Barcode, "");
document.getElementById("hdn").value = value;
var $grid = $("#jsGrid");
$grid.jsGrid("option", "editing", false);
$grid.jsGrid("option", "editing", true);
};
var **selectAll** = function (item) {
document.getElementById("hdn").value = document.getElementById("hdn").value + "," + item.Barcode;
selectedItems.push(item);
var $grid = $("#jsGrid");
$grid.jsGrid("option", "editing", false);
$grid.jsGrid("option", "editing", true);
};
var **unselectAll** = function (item) {
selectedItems = $.grep(selectedItems, function (i) {
//debugger
return i !== item;
});
var value = document.getElementById("hdn").value;
value = value.replace(item.Barcode, "");
document.getElementById("hdn").value = value;
var $grid = $("#jsGrid");
$grid.jsGrid("option", "editing", false);
$grid.jsGrid("option", "editing", true);
};
});
});
here the output image here [https://i.stack.imgur.com/gMfwn.png][1]
But noting happens can any one help me

kendo bar chart read never contatct server (cache disabled)

When some external event is triggered I need to refresh chart datasource manually calling:
$(".k-chart").data("kendoChart").dataSource.read();
Everytime I call read, datasource requestEnd is called, but, obiviously no response is available on event handler object.
I can't see any error but the webservice specified in datasource.transport.read.url is never reached after the first request.
Chart load data by server only the first time, here is the configuration:
$scope.chartopts = {
charArea: {
height: 500,
},
title: {
position: "bottom",
text: "A / B"
},
legend: {
position: "top",
visible: true
},
chartArea: {
background: "transparent"
},
seriesDefaults: {
labels: {
visible: true,
background: "transparent",
template: "#= category #: (#= value #)",
align: "alignColumn"
}
},
series: [{
startAngle: 180,
categoryField: 'category',
field: 'value',
padding: 0
}],
dataSource: {
transport: {
read: {
url: wsurl,
type: 'POST',
data: {id: id},
dataType: 'json',
cache: false,
}
},
requestEnd: function(e){
if(e.type == 'read' && e.response){//works only the first time
var rsp = [];
var a = e.response.a;
var b = e.response.b;
var tot = a + b;
if(tot!=0){
var pa = parseFloat(100 * a / tot).toFixed(2);
var pb = parseFloat(100 * b / tot).toFixed(2);
}
else {
pa = 0;
pb = 0;
}
rsp = [{
category: "A",
value: a,
color: "#66FF99",
},{
category: "B",
value: b,
color: "#FF9900",
}];
this.data(rsp);
}
}
},
tooltip: {
visible: true,
},
valueAxis: {
majorGridLines: {
visible: false
},
visible: false
},
categoryAxis: {
majorGridLines: {
visible: false
},
line: {
visible: false
}
}
};
Here is the tag:
<div kendo-chart k-options='chartopts' ></div>
I also tried to call refresh method on chart. Widget on screen is refreshed but datasource remain unchanged.
Solved defining schema property in datasource configuration object and adapting/moving all the logic from requestEnd to schema.parse method.
dataSource: {
transport: {
read: {
url: wsurl,
type: 'POST',
data: {id: id},
dataType: 'json',
cache: false,
}
},
schema: {
data: 'results',
total: 'total',
parse: function(data){
var rsp = [];
var a = data.a;
var b = data.b;
var tot = a + b;
if(tot!=0){
var pa = parseFloat(100 * a / tot).toFixed(2);
var pb = parseFloat(100 * b / tot).toFixed(2);
}
else {
pa = 0;
pb = 0;
}
rsp = {results: [{
category: "A",
value: a,
color: "#66FF99",
},{
category: "B",
value: b,
color: "#FF9900",
}], total: 2};
return rsp;
}
}
}
Everytime I need to run datasource.read(), I also refresh chart:
var chart = $(".k-chart").data("kendoChart");
chart.dataSource.read();
chart.refresh();

Restricting a Rally chart snapshot store to a date period

I want to show some data from Rally using snapshot sotre passed to teh chart like this:
storeConfig: {
find: {
_ItemHierarchy: 15312401235, //PI Object ID
//Release: 9045474054,
_TypeHierarchy: 'HierarchicalRequirement', //Burn on stories
Children: null, //Only include leaf stories,
_ValidTo: { $gte: me._startDateField.value },
_ValidFrom: { $lte: me._endDateField.value }
},
fetch: ['ScheduleState', 'PlanEstimate'],
hydrate: ['ScheduleState'],
sort: {
'_ValidFrom': 1
}
}
The idea is that I want the chart to show only yhe period between Start Date and End Date specified in me._startDateField.value and me._endDateField.value. What is the way of achieving this? Because now the chart displays the data starting from January and not from Start Date.
This example restricts the end date to a selection in the second rallydatepicker instead of defaulting to today's date. See Readme here.
Ext.define('CustomApp', {
extend: 'Rally.app.App',
componentCls: 'app',
launch: function() {
var that = this;
var minDate = new Date(new Date() - 86400000*90); //milliseconds in day = 86400000
var datePicker = Ext.create('Ext.panel.Panel', {
title: 'Choose start and end dates:',
bodyPadding: 10,
renderTo: Ext.getBody(),
layout: 'hbox',
items: [{
xtype: 'rallydatepicker',
itemId: 'from',
minDate: minDate,
handler: function(picker, date) {
that.onStartDateSelected(date);
}
},
{
xtype: 'rallydatepicker',
itemId: 'to',
minDate: minDate,
handler: function(picker, date) {
that.onEndDateSelected(date);
}
}]
});
this.add(datePicker);
var panel = Ext.create('Ext.panel.Panel', {
id:'infoPanel',
componentCls: 'panel'
});
this.add(panel);
},
onStartDateSelected:function(date){
console.log(date);
this._startDate = date;
},
onEndDateSelected:function(date){
this._endDate = date;
console.log(date);
Ext.getCmp('infoPanel').update('showing data between ' + this._startDate + ' and ' + this._endDate);
this.defineCalculator();
this.makeChart();
},
defineCalculator: function(){
var that = this;
Ext.define("MyDefectCalculator", {
extend: "Rally.data.lookback.calculator.TimeSeriesCalculator",
getMetrics: function () {
var metrics = [
{
field: "State",
as: "Open",
display: "column",
f: "filteredCount",
filterField: "State",
filterValues: ["Submitted","Open"]
},
{
field: "State",
as: "Closed",
display: "column",
f: "filteredCount",
filterField: "State",
filterValues: ["Fixed","Closed"]
}
];
return metrics;
}
});
},
makeChart: function(){
if (this.down('#myChart')) {
this.remove('myChart');
}
var timePeriod = new Date(this._endDate - this._startDate);
var project = this.getContext().getProject().ObjectID;
var storeConfig = this.createStoreConfig(project, timePeriod);
this.chartConfig.calculatorConfig.startDate = Rally.util.DateTime.format(new Date(this._startDate), 'Y-m-d');
this.chartConfig.calculatorConfig.endDate = Rally.util.DateTime.format(new Date(this._endDate), 'Y-m-d');
this.chartConfig.storeConfig = storeConfig;
this.add(this.chartConfig);
},
createStoreConfig : function(project, interval ) {
return {
listeners : {
load : function(store,data) {
console.log("data",data.length);
}
},
filters: [
{
property: '_ProjectHierarchy',
operator : 'in',
value : [project]
},
{
property: '_TypeHierarchy',
operator: 'in',
value: ['Defect']
},
{
property: '_ValidFrom',
operator: '>=',
value: interval
}
],
autoLoad : true,
limit: Infinity,
fetch: ['State'],
hydrate: ['State']
};
},
chartConfig: {
xtype: 'rallychart',
itemId : 'myChart',
chartColors: ['Red', 'Green'],
storeConfig: { },
calculatorType: 'MyDefectCalculator',
calculatorConfig: {
},
chartConfig: {
plotOptions: {
column: { stacking: 'normal'}
},
chart: { },
title: { text: 'Open/Closed Defects'},
xAxis: {
tickInterval: 1,
labels: {
formatter: function() {
var d = new Date(this.value);
return ""+(d.getMonth()+1)+"/"+d.getDate();
}
},
title: {
text: 'Date'
}
},
yAxis: [
{
title: {
text: 'Count'
}
}
]
}
}
});