Highcharts-ng with multiple series draw chart incorrectly - highcharts-ng

I have two fiddles: no angular, and using angular. The one with the angular doesn't work correctly. It doesn't show dates in xAxis, and doesn't use percent for yAxis.
Is there something specific need to be done, to have that work with angular?
No angular html
<script src="https://code.highcharts.com/stock/highstock.js"></script>
<script src="https://code.highcharts.com/stock/modules/exporting.js"></script>
<div id="container" style="height: 400px; min-width: 310px"></div>
Angular html
<script src="http://code.highcharts.com/highcharts.js"></script>
<script src="https://code.highcharts.com/stock/highstock.js"></script>
<script src="https://code.highcharts.com/stock/modules/exporting.js"></script>
<div ng-app="myApp">
<div ng-controller="myctrl">
<highchart id="chart1" config="ipo" class="span9"></highchart>
</div>
</div>
Not angular javascript
$(function () {
function createChart() {
$('#container').highcharts('StockChart', {
rangeSelector: {
selected: 4
},
yAxis: {
labels: {
formatter: function () {
return (this.value > 0 ? ' + ' : '') + this.value + '%';
}
},
plotLines: [{
value: 0,
width: 2,
color: 'silver'
}]
},
plotOptions: {
series: {
compare: 'percent'
}
},
tooltip: {
pointFormat: '<span style="color:{series.color}">{series.name}</span>: <b>{point.y}</b> ({point.change}%)<br/>',
valueDecimals: 2
},
series: [{
name: 'IPO',
data: [[1381881600000, 20.34], [1381968000000, 20.43], [1382054400000, 20.72]]
}, {
name: 'SPX',
data: [[1381881600000, 1721.54], [1381968000000, 1733.15], [1382054400000, 1744.5]]
}]
});
}
createChart();
});
Angular javascript
var myApp = angular.module('myApp', ['highcharts-ng']);
myApp.controller('myctrl', BindingCode);
myApp.factory("Factory", Factory);
function ipo() {
this.chartConfig = {
rangeSelector: {
selected: 4
},
yAxis: {
labels: {
formatter: function () {
return (this.value > 0 ? ' + ' : '') + this.value + '%';
}
},
plotLines: [{
value: 0,
width: 2,
color: 'silver'
}]
},
plotOptions: {
series: {
compare: 'percent'
}
},
tooltip: {
pointFormat: '<span style="color:{series.color}">{series.name}</span>: <b>{point.y}</b> ({point.change}%)<br/>',
valueDecimals: 2
},
series: [{
name: 'IPO',
data: [[1381881600000, 20.34], [1381968000000, 20.43], [1382054400000, 20.72]]
}, {
name: 'SPX',
data: [[1381881600000, 1721.54], [1381968000000, 1733.15], [1382054400000, 1744.5]]
}]
}
}
function BindingCode($scope,Factory) {
$scope.ipo = Factory.CreateChart();
$scope.ipo = $scope.ipo.chartConfig;
}
function Factory() {
return {
CreateChart: function () {
return new ipo();
}
}
}
Not angular screenshot
Angular screenshot

The problem is that not all the highchart options go into the top-level JSON configuration.
From the FAQ:
Why doesn't my plot options/tooltip/drilldown/other feature work?
At least half of all issues filed are due to this. Before you file an
issue read this! A common error is to put other Highcharts options
directly into the chartConfig. In general if the Highcharts option you
want isn't listed above you probably want to put it in
chartConfig.options.
In your case, you need to move pretty everything except 'series' into an options object.
chartConfig = {
options : {
rangeSelector: {
selected: 4
},
type: "line",
plotLines: [{
value: 0,
width: 2,
color: 'silver'
}],
plotOptions: {
series: {
compare: 'percent'
}
},
tooltip: {
pointFormat: '<span style="color:{series.color}">{series.name}</span>: <b>{point.y}</b> ({point.change}%)<br/>',
valueDecimals: 2
},
yAxis: {
labels: {
formatter: function () {
return (this.value > 0 ? ' + ' : '') + this.value + '%';
}
},
}
},
series: [{
name: 'IPO',
data: [[1381881600000, 20.34], [1381968000000, 20.43], [1382054400000, 20.72]]
}, {
name: 'SPX',
data: [[1381881600000, 1721.54], [1381968000000, 1733.15], [1382054400000, 1744.5]]
}]
}
Updated fiddle
https://jsfiddle.net/mgwkzob3/1/

Related

Update chart.js after form submission and page reload

I have a chart.js bar chart that pulls data via an ajax call to a Django APIView. The ajax call returns one dictionary with a stack of data inside I use to customize the chart. Here's the chart.js code:
var current_year = '{% url "saveskore:api-current-year-savings" %}'
$.ajax({
url: current_year,
type: 'GET',
cache: false,
dataType: 'json',
success: function(data) {
var ctx = document.getElementById('current-year-chart');
var chart = new Chart(ctx, {
type: 'bar',
data: {
labels: data['dates'],
datasets: [
{
label: data['income_label'],
backgroundColor: "#8e5ea2",
data: data['income'],
},
{
label: data['expense_label'],
backgroundColor: 'green',
data: data['expenses'],
},
{
label: data['savings_label'],
backgroundColor: "#3e95cd",
data: data['savings_goal'],
},
{
label: data['avail_label'],
backgroundColor: "#pink",
data: data['avail_to_spend'],
},
]
},
options: {
legend: { display: false },
title: {
display: true,
text: 'Savings for ' + data['year']
}
}
});
}
});
Works great. Looks great.
But! I have a django formset on a separate page that updates the table data that the chart pulls from.
When I update the data in the formset and submit, redirecting to the chart page ... NO UPDATE OCCURS.
If I make some code change or otherwise reload the browser, VOILA, the chart updates.
I have read about either cache=false and chart.update(), but find i have not been able to make either work, mainly because the exact details on their use are not clear.
I would really appreciate input on this.
Have you tried chart.destroy() method ? and then build again the chart with the new data .. that works for me.. take a look at my example
let flag = 0;
var xChart = "";
function dibujar(valor, meses) {
try {
if (valor.length > 0) {
$('#grafico').fadeIn('fast');
var canvas = document.getElementById('chart');
let tipGra = $('#slcTipGra').val();
if (flag !== 0) {
xChart.destroy();
}
//rgba(54, 162, 235, 0.2)
if (tipGra === "bar" || tipGra === "horizontalBar") {
var data = {
labels: meses,
datasets: [
{
label: "Dólares($)",
backgroundColor: "#3e95cd",
borderColor: "#3e95cd",
borderWidth: 2,
hoverBackgroundColor: "#3e95cd",
hoverBorderColor: "#3e95cd",
data: valor,
}
]
};
var option = {
title: {
display: true,
fontSize: 20,
fontFamily: 'Helvetica',
text: 'Reporte Mensual de Ventas'
},
plugins: {
datalabels: {
color: 'white',
anchor: 'end',
align: 'start',
font:
{
weight: 'bold'
}
}
},
scales: {
yAxes: [{
stacked: true,
gridLines:
{
display: true,
color: "rgba(255,99,132,0.2)"
}
}],
xAxes: [{
gridLines: {
display: true
}
}]
}
};
}
if (tipGra === 'line') {
var data = {
labels: meses,
datasets: [
{
label: "Dólares($)",
fill: false,
lineTension: 0.1,
backgroundColor: "rgba(75,192,192,0.4)",
borderColor: "rgba(75,192,192,1)",
borderCapStyle: 'butt',
borderDash: [],
borderDashOffset: 0.0,
borderJoinStyle: 'miter',
pointBorderColor: "rgba(75,192,192,1)",
pointBackgroundColor: "#fff",
pointBorderWidth: 1,
pointHoverRadius: 5,
pointHoverBackgroundColor: "rgba(75,192,192,1)",
pointHoverBorderColor: "rgba(220,220,220,1)",
pointHoverBorderWidth: 2,
pointRadius: 5,
pointHitRadius: 10,
data: valor,
}
]
};
var option = {
title: {
display: true,
fontSize: 20,
fontFamily: 'Helvetica',
text: 'Reporte Mensual de Ventas'
},
plugins: {
datalabels: {
backgroundColor: function (context) {
return context.dataset.borderColor;
},
borderRadius: 4,
color: 'white',
anchor: 'end',
align: 'end',
}
},
showLines: true
};
}
xChart = new Chart(canvas,
{
type: tipGra,
data: data,
options: option
});
flag = 1;
}
else {
$('#grafico').fadeOut('fast');
$('#graficoMessage').fadeIn('slow');
}
} catch (err) {
console.log(err);
}
}
I declare "xChart" as a global variable and a flag to know if it's the first chart to build. The example build 3 different types of charts (Vertical Bar, Horizontal Bar and Line) depending on the selection of the chart type "let tipGra = "$('#slcTipGra').val();"

highcharts - drilldown: does not workn with AJAX

I have a chart below that does not work with AJAX request.
function ajaxGraficoBarraUnidade() {
var strSeries = "";
var strDrilldown = "";
$.ajax({
type: "POST",
data: window.formData + '&strMundo=' + "<?php echo ($strMundo); ?>" + '&strGraph=Unidade',
dataType: "json",
url: "ajaxBlitzCarregamentoGrafico.php",
beforeSend: function () {
},
success: function (strRetorno) {
strSeries = strRetorno.geos;
strDrilldown = strRetorno.unidades;
carregaGraficoBarraUnidade(strSeries, strDrilldown);
},
error: function (txt) {
}
});
}
function carregaGraficoBarraUnidade(strSeries, strDrilldown) {
$('#divGraficoBarraUnidade').highcharts({
chart: {
type: 'column'
},
title: {
text: 'Browser market shares. January, 2015 to May, 2015'
},
subtitle: {
text: 'Click the columns to view versions. Source: netmarketshare.com.'
},
xAxis: {
type: 'category'
},
yAxis: {
title: {
text: 'Total percent market share'
}
},
legend: {
enabled: false
},
plotOptions: {
series: {
borderWidth: 0,
dataLabels: {
enabled: true,
format: '{point.y:.1f}%'
}
}
},
tooltip: {
headerFormat: '<span style="font-size:11px">{series.name}</span><br>',
pointFormat: '<span style="color:{point.color}">{point.name}</span>: <b>{point.y:.2f}%</b> of total<br/>'
},
series: strSeries,
drilldown: {
series: strDrilldown
}
});
</code>
I have a return equal to ajax below:
{'geos':[{'name': 'Regionais','data': [{'name':'Geo CO','y':1.59,'drilldown':'Geo CO'},{'name':'Geo MG/ES','y':4.41,'drilldown':'Geo MG/ES'},{'name':'Geo NE','y':3.35,'drilldown':'Geo NE'},{'name':'Geo NO','y':1.96,'drilldown':'Geo NO'},{'name':'Geo PR/SPI','y':0.10,'drilldown':'Geo PR/SPI'},{'name':'Geo RJ','y':1.81,'drilldown':'Geo RJ'},{'name':'Geo RS/SC','y':0.75,'drilldown':'Geo RS/SC'},{'name':'Geo SPC','y':0.33,'drilldown':'Geo SPC'}]}], 'unidades':[{'name':'Geo CO','id':'Geo CO','data': [['CDC Araguaina',1.30],['CDC Catalao',0.01],['CDC Formosa',4.70],['CDC Porto Velho',0.29],['CDC Rio Branco',0.00],['CDC Rio Verde',0.12],['CDC Rondonopolis',5.15],['CDC Tangara',0.51],['CDD Brasilia',0.06],['CDD Brasilia Int',2.67],['CDD Caceres',0.05],['CDD Campo Gde',0.00],['CDD Cuiaba Int',0.03],['CDD Goiania Int',0.00],['CDD Itumbiara',38.19],['CDD Manaus',0.43]]},{'name':'Geo MG/ES','id':'Geo MG/ES','data': [['CDD Alfenas',0.02],['CDD Cachoeiro',0.28],['CDD Ipatinga',0.03],['CDD João Monlevade DDC',0.00],['CDD Minas Int',0.77],['CDD Poços de Caldas',0.91],['CDD Pouso Alegre',0.17],['CDD Uberaba',0.08],['CDD Uberlandia',0.07],['CDD Vitoria',25.62],['CDL AS Minas',0.01],['CDL Santa Luzia',2.70]]},{'name':'Geo NE','id':'Geo NE','data': [['CDC Arapiraca',0.12],['CDC Lapa',0.32],['CDD Aracaju',0.05],['CDD Caruaru',8.05],['CDD F. de Santana',0.17],['CDD Guanambi',0.01],['CDD Ilheus',0.03],['CDD Maceio',0.06],['CDD Olinda',0.16],['CDD Rib. Pombal',0.04],['CDD Salvador',0.17],['CDD Vit. da Conquista',0.06],['CDL Cabo',1.33],['CDL Jequie',0.06]]},{'name':'Geo NO','id':'Geo NO','data': [['CDD Aracati',0.02],['CDD Balsas',0.08],['CDD Belem',0.02],['CDD Campina Grande',0.03],['CDD Fortaleza',0.03],['CDD Imperatriz',0.02],['CDD Joao Pessoa Int',5.86],['CDD Maranhao Int ',12.72],['CDD Natal Int',0.02],['CDD Sul Maranhão',0.03],['CDL Ceara',0.37]]},{'name':'Geo PR/SPI','id':'Geo PR/SPI','data': [['CDC Beltrao',0.00],['CDD Agudos Int',0.12],['CDD Araçatuba',0.07],['CDD Araraquara',0.02],['CDD Bebedouro',0.09],['CDD Curitiba',0.00],['CDD Jaú',3.19],['CDD Londrina',0.00],['CDD Mogi Mirim',0.04],['CDD Ponta Grossa',0.37],['CDD Presidente Prudente',0.05],['CDD Rib. Preto',0.04],['CDL Paranagua',0.02]]},{'name':'Geo RJ','id':'Geo RJ','data': [['CDD Campos',1.18],['CDD Jacarepagua',1.65],['CDD Niteroi',0.02],['CDD Nova Friburgo',0.01],['CDD Nova Iguacu',0.02],['CDD Petropolis',0.00],['CDD RJ Campo Gde Int',3.77],['CDD S. Cristovao',0.81],['CDL Itaperuna',0.14]]},{'name':'Geo RS/SC','id':'Geo RS/SC','data': [['CDD Blumenau',0.07],['CDD Camboriu',0.11],['CDD Caxias do Sul',0.07],['CDD Florianopolis',0.12],['CDD Pelotas',0.04],['CDD Porto Alegre',1.06],['CDD S. Cruz Sul',0.02],['CDD Santa Maria',0.45],['CDD Sapucaia Int',2.66]]},{'name':'Geo SPC','id':'Geo SPC','data': [['CDD Campinas',0.12],['CDD Diadema',0.72],['CDD Guarulhos',0.23],['CDD Jundiai',1.04],['CDD Litoral SP',0.05],['CDD Mooca',1.05],['CDD Norte',0.10],['CDD Oeste',0.04],['CDD Praia Grande',0.06],['CDD São José dos Campos',0.54],['CDD Sul SP',0.00],['CDD Taubaté',0.82],['CDD Votorantin',0.77]]}]}
It does not recognize the values passed in SERIES. I do not think the error. Does anyone know what might be happening? Tanks!
What might be happening is your data is getting loaded after the chart is created, so I've changed the format to be as shown in the Highcharts documentation, but tried not to change to much otherwise.
Highcharts documentation on working with data
See a plunkr demo with your chart working with available data
The data is hosted on myjson.com as JSON, so I changed the POST to a GET request.
Here is the key HTML code:
<script src="https://code.jquery.com/jquery-3.0.0.min.js" integrity="sha256-JmvOoLtYsmqlsWxa7mDSLMwa6dZ9rrIdtrrVYRnDRH0=" crossorigin="anonymous"></script>
<script src="http://code.highcharts.com/highcharts.js"></script>
<div id="divGraficoBarraUnidade" style="width:100%; height:400px;"></div>
This is the Javascript / jQuery code:
$(function () {
$(document).ready(function() {
var options = {
chart: {
renderTo: 'divGraficoBarraUnidade',
type: 'column'
},
title: {
text: 'Browser market shares. January, 2015 to May, 2015'
},
subtitle: {
text: 'Click the columns to view versions. Source: netmarketshare.com.'
},
xAxis: {
type: 'category'
},
yAxis: {
title: {
text: 'Total percent market share'
}
},
legend: {
enabled: false
},
plotOptions: {
series: {
borderWidth: 0,
dataLabels: {
enabled: true,
format: '{point.y:.1f}%'
}
}
},
tooltip: {
headerFormat: '<span style="font-size:11px">{series.name}</span><br>',
pointFormat: '<span style="color:{point.color}">{point.name}</span>: <b>{point.y:.2f}%</b> of total<br/>'
},
series: {},
drilldown: {
series: {}
}
};
function ajaxGraficoBarraUnidade() {
$.ajax({
type: "GET",
data: window.formData + '&strMundo=' + "<?php echo ($strMundo); ?>" + '&strGraph=Unidade',
dataType: "json",
url: "https://api.myjson.com/bins/42c59",
beforeSend: function () {
},
success: function (strRetorno) {
options.series = strRetorno.geos;
options.drilldown.series = strRetorno.unidades;
var chart = new Highcharts.Chart(options);
console.log('options', options)
},
error: function (txt) {
// Report errors here...
}
});
}
ajaxGraficoBarraUnidade();
});
});

How to add hyperlink in resources in kendo-UI scheduler

I have a scheduler (timeline view) set up that produces an interface that looks like the attached image.
[![scheduler_screenshot][1]][1]
The resources part of the scheduler code looks like this:
, resources: [
{
field: "loca_ky"
, name: "Locations"
, dataSource: [
{text:"CHAR above entrance doors", value:1},
{text:"BELLIARD Passerelle", value:2},
{text:"BERL Schuman", value:3}
]
, title: "Location"
}
]
I want the users to be able to find out more about the locations (eg. 'CHAR above entrance doors', etc) and therefore want to provide either a hyperlink around the text, or maybe add an icon with a hyperlink.
How do I do this?
Response to answers
Hi Jayesh
Re. Method 1. Adding the new function afterthe script fails to work because I am already using the 'databound' node of the scheduler as a function. See code below:
, dataBound: function(e) {
// hide the times row from the date/time header:
var view = this.view();
view.datesHeader.find("tr:last").prev().hide();
view.timesHeader.find("tr:last").prev().hide();
// Switch the colour of the reservation depending on stat_ky
$('div.k-event').removeClass('special-event'); // Remove the widget default colour.
$('div.k-event').addClass('eventRequested'); // Add back the eventRequested colour, which we use for every stage up to BOOKED.
e.sender._data.forEach(function(eventDetails) {
if (eventDetails['stat_ky'] == 5) {
// Switch the colour to eventAccepted for BOOKED requests (stat_ky=5).
$('div.k-event[data-uid="'+eventDetails['uid']+'"]').addClass('eventAccepted');
}
});
}
Should I place your code inside this function?
Response to answers, 2
Hi Jayesh
Yes, this works well indeed!
One final snag. In your example here is the datasource of the resource:
dataSource: [
{ text: "Meeting Room 101", value: 1, color: "#6eb3fa" },
{ text: "Meeting Room 201", value: 2, color: "#f58a8a" }
],
And you get the 'text' using element.html() like this:
element.html("<a href='http://google.com/" + element.html() + "'>" + element.html() + "</a>");
How do I reference the 'value' of the resource?
You can achieve this thing by using below two different methods.
Method 1: Manually converting resources text into hyperlink
<!DOCTYPE html>
<html>
<head>
<base href="http://demos.telerik.com/kendo-ui/scheduler/resources-grouping-vertical">
<style>
html {
font-size: 14px;
font-family: Arial, Helvetica, sans-serif;
}
</style>
<title></title>
<link rel="stylesheet" href="//kendo.cdn.telerik.com/2016.1.412/styles/kendo.common-material.min.css" />
<link rel="stylesheet" href="//kendo.cdn.telerik.com/2016.1.412/styles/kendo.material.min.css" />
<script src="//kendo.cdn.telerik.com/2016.1.412/js/jquery.min.js"></script>
<script src="//kendo.cdn.telerik.com/2016.1.412/js/kendo.all.min.js"></script>
<script src="//kendo.cdn.telerik.com/2016.1.412/js/kendo.timezones.min.js"></script>
</head>
<body>
<div id="example" class="k-content">
<div id="scheduler"></div>
</div>
<script>
$(function () {
$("#scheduler").kendoScheduler({
date: new Date("2013/6/13"),
startTime: new Date("2013/6/13 07:00 AM"),
height: 600,
views: [
"day",
{ type: "week", selected: true },
"month",
"agenda",
"timeline"
],
timezone: "Etc/UTC",
dataBound: scheduler_dataBound,
dataSource: {
batch: true,
transport: {
read: {
url: "https://demos.telerik.com/kendo-ui/service/meetings",
dataType: "jsonp"
},
update: {
url: "https://demos.telerik.com/kendo-ui/service/meetings/update",
dataType: "jsonp"
},
create: {
url: "https://demos.telerik.com/kendo-ui/service/meetings/create",
dataType: "jsonp"
},
destroy: {
url: "https://demos.telerik.com/kendo-ui/service/meetings/destroy",
dataType: "jsonp"
},
parameterMap: function (options, operation) {
if (operation !== "read" && options.models) {
return { models: kendo.stringify(options.models) };
}
}
},
schema: {
model: {
id: "meetingID",
fields: {
meetingID: { from: "MeetingID", type: "number" },
title: { from: "Title", defaultValue: "No title", validation: { required: true } },
start: { type: "date", from: "Start" },
end: { type: "date", from: "End" },
startTimezone: { from: "StartTimezone" },
endTimezone: { from: "EndTimezone" },
description: { from: "Description" },
recurrenceId: { from: "RecurrenceID" },
recurrenceRule: { from: "RecurrenceRule" },
recurrenceException: { from: "RecurrenceException" },
roomId: { from: "RoomID", nullable: true },
attendees: { from: "Attendees", nullable: true },
isAllDay: { type: "boolean", from: "IsAllDay" }
}
}
}
},
group: {
resources: ["Rooms", "Attendees"],
orientation: "vertical"
},
resources: [
{
field: "roomId",
name: "Rooms",
dataSource: [
{ text: "Meeting Room 101", value: 1, color: "#6eb3fa" },
{ text: "Meeting Room 201", value: 2, color: "#f58a8a" }
],
title: "Room"
}
]
});
});
// Below function is converting text into hyperlink
function scheduler_dataBound(e) {
$("#scheduler").find(".k-slot-cell").each(function () {
var element = $(this);
if (element != null) {
if (element.context.textContent.length > 2) {
element.html("<a href='http://google.com/" + element.html() + "'>" + element.html() + "</a>");
}
}
});
}
</script>
</body>
</html>
Method 2: By using template
Demo
Let me know if any concern.

kendo UI bar chart- how to move the X axis

Here is the link for kendo UI bar chart: http://jsfiddle.net/nayanakalkur/ZPUr4/119/
In the fiddle example, X-axis is at '0'. How can i move the axis up or down the Y axis?
Suppose i want have the X-axis at 'y' value 10? How can this be done?
Code for the same:
HTML code:
<div id="example" class="k-content">
<div id="chart"></div>
</div>
Javascript code:
function createChart() {
$("#chart").kendoChart({
title: {
text: "Site Visitors"
},
legend: {
position: "bottom"
},
seriesDefaults: {
type: "column",
labels: {
visible: true,
background: "transparent",
}
},
series: [{
name: "Total Visits",
data: series1,
gap: 1.0,
spacing: 0
}, {
name: "Unique visitors",
data: series2,
gap: 1.0
}],
valueAxis: {
line: {
visible: false
},
title: {
text: "Availability"
}
},
categoryAxis: {
majorGridLines: {
visible: true,
position: "bottom"
}
},
tooltip: {
visible: true,
format: "{0}"
}
});
}
var series1=[56000, 63000, 74000, 91000, 117000, 158000];
var series2= [-52000, 34000, 23000, -98000, 67000, 83000];
$(document).ready(function () {
createChart();
$("#example").bind("kendo:skinChange", createChart);
var chart = $("#chart").data("kendoChart"),
firstSeries = chart.options.series;
});
Thanks in advance.
Set valueAxis.min to 10:
valueAxis: {
min: 10,
line: {
visible: false
},
title: {
text: "Availability"
}
},
Your JSFiddle modified in here: http://jsfiddle.net/OnaBai/ZPUr4/120/
EDIT: If you want that the axis crosses at one specific value, then set valueAxis.axisCrossingValue to the value.
Example:
valueAxis: {
axisCrossingValue: -50000,
line: { visible: false },
title: { text: "Availability" },
},
And the JSFiddle modified http://jsfiddle.net/OnaBai/ZPUr4/126/

Based on selection is it possible to change value axis

I have a requirement i.e based on the tree view check box selection the value axis need to update.I am using 4 check boxes with 4 value axis.when ever I check the first item corresponding value axis should be changed .3 other axis should in invisible state.
Here I tried with some of the code and updated .
Code:
<div id="treeview"></div>
<div id="example" class="k-content">
<div class="chart-wrapper">
<div id="chart"></div>
</div>
</div>
var valueAxes = [
{ name: "KM",visible:false,
title: { text: "KM" ,visible:false}
},
{ name: "Miles Per Gallon",
title: { text: "Miles Per Gallon" }
},
{
name: "Miles",
title: { text: "Miles " }
},
{
name: "liters per 100km",
title: { text: "liters per 100km" }
}
];
function createChart() {
$("#chart").kendoChart({
legend: {
position: "top"
},
series: [{
type: "column",
data: [20, 40, 45, 30, 50],
stack: true,
name: "on battery",
color: "#003c72"
}, {
type: "column",
data: [20, 30, 35, 35, 40],
stack: true,
name: "on gas",
color: "#0399d4"
}, {
type: "area",
data: [30, 38, 40, 32, 42],
name: "mpg",
color: "#642381"
}, {
type: "area",
data: [7.8, 6.2, 5.9, 7.4, 5.6],
name: "l/100 km",
color: "#e5388a"
}],
valueAxes:valueAxes,
categoryAxis: {
categories: ["Mon", "Tue", "Wed", "Thu", "Fri"],
axisCrossingValues: [0, 0, 10, 10]
}
});
}
$(document).ready(function() {
createChart();
$("#treeview").kendoTreeView({
checkboxes: {
checkChildren: true
},
dataSource: [{
id: 1,
text: "Value axis",
expanded: true,
items: [{
id: 2,
text: "KM"
},
{
id: 3,
text: "Miles Per Gallon"
},
{
id: 4,
text: "Miles "
},
{
id: 5,
text: "liters per 100km"
}]
}]
}).data("kendoTreeView");
$("#treeview").on("change", function (e) {
var chart = $("#chart").data("kendoChart");
var checkedSeries = [];
$("#treeview").find(":checked").each(function() {
var nodeText =$(this).parent().parent().text();
$.each(valueAxes, function(index, valueAxes) {
if (valueAxes.name == nodeText) {
checkedSeries.push(valueAxes);
checkedSeries.visible==="true";
checkedSeries.title.visible===true;
}
});
});
chart.options.valueAxes = checkedSeries;
chart.refresh();
});
});
jsbin: Value axis change
Yes , it is possible to bind and unbind value axis and series at a time.
Change your scripts like below
var valueAxes = [
{
name: "KM", labels: {
format: "{0}"
}, min: 0,
max: 9,
title: { text: "KM" }
},
{
name: "Miles Per Gallon", labels: {
format: "{0}%"
}, min: 0,
max: 5,
title: { text: "Miles Per Gallon" }
},
{
name: "Miles", labels: {
format: "{0}%"
},
title: { text: "Miles " }
},
{
name: "liters per 100km", min: 0,
max: 1,
title: { text: "liters per 100km" }
}];
var series = [{
type: "column",
axis: "KM",
data: [20, 40, 45, 30, 50],
stack: true,
name: "KM",
color: "#003c72"
}, {
type: "column",
data: [20, 30, 35, 35, 40],
axis: "Miles Per Gallon",
stack: true,
name: "Miles Per Gallon",
color: "#0399d4"
}, {
type: "column",
data: [30, 38, 40, 32, 42],
axis: "Miles",
name: "Miles",
color: "#642381"
}, {
type: "column",
axis: "liters per 100km",
data: [7.8, 6.2, 5.9, 7.4, 5.6],
name: "liters per 100km",
color: "#e5388a"
}];
function createChart(inputValueAxes, inputSeries) {
$("#chart").kendoChart({
legend: {
position: "top"
},
series: inputSeries,
valueAxes: inputValueAxes,
categoryAxis: {
categories: ["Mon", "Tue", "Wed", "Thu", "Fri"],
axisCrossingValues: [0, 0, 10, 10]
}
});
}
$(document).ready(function () {
createChart(valueAxes, series);
$("#treeview").kendoTreeView({
checkboxes: {
checkChildren: true
},
dataSource: [{
id: 1,
text: "Value axis",
expanded: true,
items: [{
id: 2,
text: "KM"
},
{
id: 3,
text: "Miles Per Gallon"
},
{
id: 4,
text: "Miles "
},
{
id: 5,
text: "liters per 100km"
}]
}]
}).data("kendoTreeView");
$("#treeview").on("change", function (e) {
var chart = $("#chart").data("kendoChart");
var checkedSeries = [];
var checkedAxes = [];
if ($("#treeview").find(":checked").length !== 0) {
$("#treeview").find(":checked").each(function () {
var nodeText = $(this).parent().parent().text();
$.each(valueAxes, function (index, valueAxes) {
if (valueAxes.name == nodeText.trim()) {
checkedAxes.push(valueAxes);
checkedAxes.visible = true;
}
});
$.each(series, function (index, series) {
if (series.name == nodeText.trim()) {
checkedSeries.push(series);
}
});
});
createChart(checkedAxes, checkedSeries);
}
else {
createChart(checkedAxes, checkedSeries);
}
});
});
Refer this http://jsbin.com/eyibar/49/edit
For convenience, Intially i load all the chart axeses. Its working as you asked....
jsbin: http://jsbin.com/eyibar/37/edit
<html>
<head>
<link href="http://cdn.kendostatic.com/2013.1.319/styles/kendo.common.min.css" rel="stylesheet" type="text/css" />
<link href="http://cdn.kendostatic.com/2013.1.319/styles/kendo.rtl.min.css" rel="stylesheet" type="text/css" />
<link href="http://cdn.kendostatic.com/2013.1.319/styles/kendo.default.min.css" rel="stylesheet" type="text/css" />
<link href="http://cdn.kendostatic.com/2013.1.319/styles/kendo.dataviz.min.css" rel="stylesheet" type="text/css" />
<link href="http://cdn.kendostatic.com/2013.1.319/styles/kendo.dataviz.default.min.css" rel="stylesheet" type="text/css" />
<link href="http://cdn.kendostatic.com/2013.1.319/styles/kendo.mobile.all.min.css" rel="stylesheet" type="text/css" />
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script src="http://cdn.kendostatic.com/2013.1.319/js/kendo.all.min.js"></script>
<meta charset="utf-8" />
<title>JS Bin</title>
<style>
#chart { width: 600px; }
</style>
</head>
<body>
<div id="treeview"></div>
<div id="example" class="k-content">
<div class="chart-wrapper">
<div id="chart"></div>
</div>
</div>
<script type="text/javascript">
var valueAxes = [
{
name: "KM",
title: { text: "KM" }
},
{
name: "Miles Per Gallon",
title: { text: "Miles Per Gallon" }
},
{
name: "Miles",
title: { text: "Miles " }
},
{
name: "liters per 100km",
title: { text: "liters per 100km" }
}];
function createChart(valueAxes) {
$("#chart").kendoChart({
legend: {
position: "top"
},
series: [{
type: "column",
data: [20, 40, 45, 30, 50],
stack: true,
name: "on battery",
color: "#003c72"
}, {
type: "column",
data: [20, 30, 35, 35, 40],
stack: true,
name: "on gas",
color: "#0399d4"
}, {
type: "area",
data: [30, 38, 40, 32, 42],
name: "mpg",
color: "#642381"
}, {
type: "area",
data: [7.8, 6.2, 5.9, 7.4, 5.6],
name: "l/100 km",
color: "#e5388a"
}],
valueAxes: valueAxes,
categoryAxis: {
categories: ["Mon", "Tue", "Wed", "Thu", "Fri"],
axisCrossingValues: [0, 0, 10, 10]
}
});
}
$(document).ready(function () {
createChart(valueAxes);
$("#treeview").kendoTreeView({
checkboxes: {
checkChildren: true
},
dataSource: [{
id: 1,
text: "Value axis",
expanded: true,
items: [{
id: 2,
text: "KM"
},
{
id: 3,
text: "Miles Per Gallon"
},
{
id: 4,
text: "Miles "
},
{
id: 5,
text: "liters per 100km"
}]
}]
}).data("kendoTreeView");
$("#treeview").on("change", function (e) {
var chart = $("#chart").data("kendoChart");
var checkedSeries = [];
if ($("#treeview").find(":checked").length != 0) {
$("#treeview").find(":checked").each(function () {
var nodeText = $(this).parent().parent().text();
$.each(valueAxes, function (index, valueAxes) {
if (valueAxes.name == nodeText.trim()) {
checkedSeries.push(valueAxes);
checkedSeries["visible"] = true;
}
});
});
createChart(checkedSeries);
}
else {
createChart(checkedSeries);
}
});
});
</script>
</body>
</html>
I edited your code in that I can able to bind and unbind the valueaxis by calling the creatChart(checkedAxes) function in if condition with length==-1,at that time the series is not updated.
$("#treeview").on("change", function (e) {
var chart = $("#chart").data("kendoChart");
var checkedSeries = [];
var checkedAxes = [];
if ($("#treeview").find(":checked").length !== -1){
$("#treeview").find(":checked").each(function () {
var nodeText = $(this).parent().parent().text();
$.each(valueAxes, function (index, valueAxes) {
if (valueAxes.name == nodeText) {
checkedAxes.push(valueAxes);
checkedAxes.visible = true;
}
});
$.each(series, function (index, series) {
if (series.name == nodeText) {
checkedSeries.push(series);
}
});
});
chart.options.series = checkedSeries;
chart.options.valeAxes = checkedAxes;
chart.refresh();
}
createChart(checkedAxes);
});
but if I tried by without calling the creatChart(checkedAxes) function,the series binded to the chart are updated.
$("#treeview").on("change", function (e) {
var chart = $("#chart").data("kendoChart");
var checkedSeries = [];
var checkedAxes = [];
if ($("#treeview").find(":checked").length !== -1){
$("#treeview").find(":checked").each(function () {
var nodeText = $(this).parent().parent().text();
$.each(valueAxes, function (index, valueAxes) {
if (valueAxes.name == nodeText) {
checkedAxes.push(valueAxes);
checkedAxes.visible = true;
}
});
$.each(series, function (index, series) {
if (series.name == nodeText) {
checkedSeries.push(series);
}
});
});
chart.options.series = checkedSeries;
chart.options.valeAxes = checkedAxes;
chart.refresh();
}
});
I didn't get the both scenarios at a time.sorry,hope you find the solution.
Cheers,
Happy Coding...

Resources