SetData() not working on Change Event HighCharts Pie Chart - javascript

I'm looking for a way to dynamically update data in a highcharts pie chart based on the change event on a dropdownlist. I have seen a couple examples but I am really unable to figure out why I can't get this working. Here is my whole code, I wrap my stuff inside a function so I can call the function with the Change() event of the dropdownlist, but I get the error of CRIPT438: Object doesn't support property or method 'setData'
function showClass(){
var total = 0;
var options = {
chart:{type:'pie',
renderTo: 'ctl00_ContentPlaceHolder1_Overview1_tcAssetAllocation_body',
events: {
load: function(event) {
$('.highcharts-legend-item').last().append('<br/><div style="width:220px"><hr/> <span style="float:left"> Total </span><span style="float:right">100%</span> </div>')
}
}
},
credits:{enabled: false},
colors:[
'#5485BC', '#AA8C30', '#5C9384', '#981A37', '#FCB319', '#86A033', '#614931', '#00526F', '#594266', '#cb6828', '#aaaaab', '#a89375'
],
title:{text: null},
tooltip:{
enabled: true,
animation: true
},
plotOptions: {
pie: {
allowPointSelect: true,
animation: true,
cursor: 'pointer',
showInLegend: true,
dataLabels: {
enabled: false,
formatter: function() {
return this.percentage.toFixed(2) + '%';
}
}
}
},
legend: {
enabled: true,
layout: 'vertical',
align: 'right',
width: 220,
verticalAlign: 'top',
borderWidth: 0,
useHTML: true,
labelFormatter: function() {
total += this.y;
return '<div style="width:200px"><span style="float:left">' + this.name + '</span><span style="float:right">' + this.y + '%</span></div>';
},
title: {
text: 'Primary',
style: {
fontWeight: 'bold'
}
}
},
series: [{
type: 'pie',
data: [['Domestic Equity', 38.5],['International Equity', 26.85],['Other', 15.70],['Cash and Equivalents', 10.48],['Fixed Income', 8.48]]
}]
}
var chart = new Highcharts.Chart(options);
$("#ctl00_ContentPlaceHolder1_Overview1_AccountList1_ddlAccounts").change(function(){
var selVal = $("#ctl00_ContentPlaceHolder1_Overview1_AccountList1_ddlAccounts").val();
if(selVal == '1124042'){
chart.series[0].setData([['Domestic Equity', 18.5], ['International Equity', 46.85], ['Other', 5.70], ['Cash and Equivalents', 20.48], ['Fixed Income', 8.48]]); }
});
}
is it because i am nested inside another function? it's jsut that all the fiddles use the document.ready function and it loads properly calling the function in the document.ready() but getting it on the change event is messing with me.
Any help is greatly appreciated.
Tahnk you very much,
NickG

You are wrong to use object options as part of Highcharts API. Find that line: options.series[0].setData and change to chart.series[0].setData(). Then remove creating new chart ( you don't need that - chart is already created ).

Related

Changing tootip data on pie chart in highcharts

I have been trying to edit the pie chart on this website using the config method:
Change colours (working)
Show legend (working)
Click legend to activate chart section (working)
Donut sizing (working)
Tooltip different data (not working)
Legend showing percentages (not working)
I can't, for the life of me, get the legend to show the percentages and I can't get the tooltip data to change.
Currently, the tooltip says, for example:
Australian equities
Percentage: 40%
I need the tooltip to say:
Australian equities: 40%
Currently, the legend says, for example:
Australian equities
I need the legend to say:
40% Australian equities
<script type="text/javascript">
jQuery(window).on('load',function(){
if( typeof wpDataChartsCallbacks == 'undefined' ){ wpDataChartsCallbacks = {}; }
wpDataChartsCallbacks[1] = function(obj){
obj.options.plotOptions = {
series: {
dataLabels: {
enabled: false
}
},
pie: {
colors: [
'#006769',
'#00b8af',
'#28c3e8',
'#0ee4da',
'#2a97a6'
],
allowPointSelect: true,
cursor: 'pointer',
dataLabels: {
enabled: false
},
size: 340,
innerSize: '50%',
showInLegend: true,
point: {
events: {
legendItemClick: function () {
this.select();
return false;
}
}
}
},
tooltip: {
formatter: function() {
return this.point.name + ': <b>' + Highcharts.numberFormat(this.y, 1) +'%</b>';
}
},
legend: {
labelFormatter: function() {
return '<strong style="display:inline-block;width:45px;">'+Highcharts.numberFormat(this.y, 1) +'%</strong> ' + this.name ;
},
title: {
style: {
fontSize: '18px',
fontFamily: "'neuzeit-grotesk', sans-serif",
color: '#20242b'
},
text : 'By industry'
},
squareSymbol: true,
},
};
};
});
</script>
This chart is feeding from a locally stored excel spreadsheet to reflect live data which is why the config method must be used.
I have read other threads and the highcharts forums but when I copy the codes into the above it still doesn't change the legend and tooltop.
Any help would be greatly appreciated.
You should implement legend and tooltip configuration on the highest level:
{
...,
tooltip: {
formatter: function() {
...
}
},
legend: {
labelFormatter: function() {
...
},
...
}
}
Live demo: http://jsfiddle.net/BlackLabel/9sp4m1cf/
API Reference:
https://api.highcharts.com/highcharts/tooltip.formatter
https://api.highcharts.com/highcharts/legend.labelFormatter

Highcharts variable pie legendItemClick does not hide or update data

I am currently working with HighCharts variable Pie chart. I wanted to add more functionality to the legend click, so I added a separate legendItemClick event to perform two things: it should behave like the default (which it doesn't), but also correct the text value inside the donut, which also does not work.
Here is some code to work with:
this._chart = Highcharts.chart(this.$.chartsContainer, {
title: {
text: '<div style="font-size: 30px; font-weight:600;">' + ySum + '</div><div>Total demands</div>',
align: 'center',
verticalAlign: 'middle',
useHTML: true,
style: {
'font-size': '16px',
'font-weight': 'normal',
'text-align': 'center',
'text-transform': 'inherit'
},
x: -2,
y: -27,
},
colors: ['#315674', '#006281', '#006D81', '#00BFE2', '#53A1B4', '#4FB4B5', '#00E8D2', '#FFC35F', '#9ECBD6'],
plotOptions: {
series: {
dataLabels: {
enabled: false },
showInLegend: true,
style: {'border-radius': '15px', 'font-weight': 'normal'},
},
variablepie: {
name: '',
borderWidth: 5, borderColor: 'white', minPointSize: 16,
color: 'white', innerSize: '60%',
point: {
events: {
legendItemClick: function(event) {
console.log(event);
if (this.visible) {
this.series.visible = false;
ySum = ySum - event.target.options.y;
} else {
ySum = ySum + event.target.options.y;
}
}
}
}
},
},
tooltip: {
useHTML: true,
headerFormat: '<small>{point.y}</small><table>',
pointFormat: '',
footerFormat: ''
},
series: [{
type: 'variablepie',
data: ySerie,
},
]
});
this.reflowChart();
I tried hiding the clicked series data via its visible attribute, but that does not work properly, because it hides the clicked data, but does not redraw the chart to form a full circle again ( if you know what I am talking about ).
The second problem is the text title. I want it to show the new corrected value ( it is the ySum variable up inside the title: { text: block ). I tried setting the new value but it does not update the chart's data for some reason. For example, we have 3 slices of value 10 each. It shows "30 total". When 1 legend item is clicked and hidden, it should update ySum to now show " 20 total".
So in short, I need help with
1) How to properly hide and show clicked legend series data
2) Make the text attribute ySum update its value accordingly
Thank you for your help!
------------------- UPDATE -----------------
I figured out the first problem by myself ( I will leave the problem nonetheless if anyone else faces it ):
legendItemClick event is a function that can return a boolean value:
You can manipulate its behavior by setting
true = standard behavior -> it will hide the data series AND redraw the chart
false = it will do nothing -> similar as event.preventDefault()
To change chart title you can use setTitle method:
legendItemClick: function(event) {
var chart = this.series.chart
if (this.visible) {
// this.series.visible = false;
ySum = ySum - event.target.options.y;
} else {
ySum = ySum + event.target.options.y;
}
chart.setTitle({
text: ySum
}, false, false);
return true
}
API Reference: https://api.highcharts.com/class-reference/Highcharts.Chart#setTitle
Live demo: https://jsfiddle.net/BlackLabel/sdh1y0tw/

Highcharts - Display legend for Pie chart in two columns

I have been using Highcharts(v2.1.9) to generate some pie charts. The charts are generated quite well, however I am having some problems with displaying the legend.
The legend shows in vertical view, but instead of all the legend items showing, some are hidden. I believe this is due to the navigation option being automatically enabled, which pages all of the other legend items that do not fit within the container.
Instead of paging the rest of the legend items, I want to show them in a second column, side by side with the first column.
This data is dynamic so the number of legend items/pie sectors may change over time. The solution must be able to handle more than two columns if the sectors increase.
I think one way to turn off the navigation option is to use the useHTML: true option but I haven't been able to style it in the way that I want.
Here is the fiddle: http://jsfiddle.net/7fb3x9ys/
$(function () {
$(document).ready(function () {
// Build the chart
$('#container').highcharts({
chart: {
plotBackgroundColor: null,
plotBorderWidth: null,
plotShadow: false,
borderWidth: 0,
width: 800,
height: 280
},
credits: {
enabled: false
},
legend: {
borderWidth: 0,
labelFormatter: function() {
var total = 0, percentage;
$.each(this.series.data, function() {
total+=this.y;
});
percentage=((this.y/total)*100).toFixed(2);
return '<span style="color:#000000,font-size:12px !important;"><b>'+ this.name + '</b></span><br/><span style="color:#000000,font-size:12px !important;">'+percentage+'%</span>';
},
verticalAlign: 'middle',
x:185,
y:0,
layout: 'vertical',
width: 600,
height:280,
itemWidth: 600,
symbolWidth: 7,
symbolHeight: 28
},
title: {
text: ''
},
tooltip: {
pointFormat: '{series.name}: <b>{point.percentage:.1f}%</b>'
},
plotOptions: {
pie: {
allowPointSelect: true,
cursor: 'pointer',
size: 275,
center: ["16%", "50%"],
dataLabels: {
enabled: false,
},
showInLegend: true,
minSize: 130,
colors: [
'#7DA0B0',
'#9264AA',
'#4F2A72',
'#9A3968',
'#BF5269',
'#E16553',
'#E3985E',
'#E4BF80',
'#75C494',
'#52584B'
]
}
},
series: [{
type: 'pie',
name: 'Sector',
data:{"data":[["ENERGY",17.4],["FINANCIALS",15.1],["CONSUMER STAPLES",14.9],["UTILITIES",14.88],["MATERIALS",7.59],["REAL ESTATE",7.24],["TELECOMMUNICATION SERVICES",7.08],["CONSUMER DISCRETIONARY",6.95],["INDUSTRIALS",5.28],["HEALTH CARE",2.64],["CASH",0.95]]}.data
}]
});
});
});
I want to thank all responses in advance. I have been stuck on this for a few days now and any help would be greatly appreciated.
You can try laying out the legends horizontally and setting itemWidth to something greater than 80. That worked for me.
Example:
legend: {
itemWidth: 80
}

Add legend name to JQPlot tooltip and format date correctly in tool tip

I want to add the plot's legend name to the mouse over tool tip for a series line. I've used one of the solutions to this jqplot tooltip on bar chart.
Specifically I used the following function:
function tooltipContentEditor(str, seriesIndex, pointIndex, plot) {
// display series_label, x-axis_tick, y-axis value
return plot.series[seriesIndex]["label"] + ", " + plot.data[seriesIndex][pointIndex];
}
However, the problem I have is that it does not use the legend name 'My legend name' instead it will use the JQPlot default of 'Series 1' or 'Series 5' (number depending on series position).
The second problem is that I lose my date formatting once I start using the above function. So I get a number e.g. something like 123672378328 instead of it being converted to the format I specified in tickOptions.
My code to generate the chart is below:
var plot;
function buildChart(chartDivId, graphData, chartTitle, graphSeriesNames, labelNames) {
var id = "#" + chartDivId;
$(id).empty();
var seriesLine = { lineWidth:1, markerOptions: { show:false } };
plot = $.jqplot(chartDivId, graphData,
{
title: chartTitle,
axes:
{
xaxis:
{
label:'Date',
renderer:$.jqplot.DateAxisRenderer,
tickOptions: { formatString:'%b %#d %H:%M' }
},
yaxis: { label: 'Parameter Values', tickOptions: { formatString:'%.2f' }, labelRenderer: $.jqplot.CanvasAxisLabelRenderer, labelOptions : { angle: 270, fontFamily: 'Arial, Verdana, Helvetica', fontSize: '8pt' }, autoscale: true },
},
seriesDefaults: {
markerOptions: {
show: true, style:'filledCircle', size: 4.5
}
},
highlighter:
{
show: true,
sizeAdjust: 7.5,
tooltipContentEditor:tooltipContentEditor //new code added to attempt to add legend name to mouse over tool tip
},
cursor:
{
show: true,
zoom: true,
showTooltip: false
},
legend:
{
labels: labelNames ,
show: true,
location: 's',
renderer: $.jqplot.EnhancedLegendRenderer,
rendererOptions:
{
numberColumns: 10,
numberRows: 5,
seriesToggle: 900,
disableIEFading: false
},
marginTop: '100px',
marginBottom: '100px',
placement: 'outside'
}
}
);
}
FURTHER UPDATE:
After being a bit silly and digging down deep into the plot object of JQPlot I realised that the str variable passed into the tooltipContentEditor method has what I need. So the following is the solution:
function tooltipContentEditor(str, seriesIndex, pointIndex, plot) {
// display series_label with x and y values value
return plot.legend.labels[seriesIndex] + ", " + str;
}
No help or advice provided so I thought I'd provide the solution I found after spending a few hours trying to fix.

Highcharts X-Axis New Values

I am using highcharts to draw a column chart as following:
var chart;
var count = 0;
$(function () {
$(document).ready(function() {
chart = new Highcharts.Chart({
chart: {
renderTo: 'graph',
type: 'column',
margin: [ 50, 50, 100, 80]
},
title: {
text: 'Random Data'
},
xAxis: {
categories: [
'T1',
'T2'
],
startOnTick: true,
endOnTick: true,
labels: {
rotation: -45,
align: 'right',
style: {
fontSize: '13px',
fontFamily: 'Verdana, sans-serif'
}
}
},
yAxis: {
min: 0,
title: {
text: 'Y-Axis'
}
},
legend: {
enabled: false
},
tooltip: {
formatter: function() {
return '<b>'+ this.x +'</b><br/>'+
'Tip is: '+ Highcharts.numberFormat(this.y, 1);
}
},
series: [{
name: 'Population',
data: [34.4, 21.8],
dataLabels: {
enabled: true,
rotation: -90,
color: '#FFFFFF',
align: 'right',
x: 4,
y: 10,
style: {
fontSize: '13px',
fontFamily: 'Verdana, sans-serif'
}
}
}]
});
});
});
I added the following function in order to add new points to the chart
function addPoints(name,acc)
{
var series = chart.series[0];
series.addPoint(acc, false, true);
categories = chart.xAxis[0].categories;
categories.push(name+count);
count++;
chart.xAxis[0].setCategories(categories, false);
chart.redraw();
}
The problem is that everytime I add a new point, one column shifts out of the chart. I would like to keep all columns in the chart view, so when I add a new point the chart just zooms out.
Check it on JSFiddle
Thanks in Advance ....
addPoint (Object options, [Boolean redraw], [Boolean shift], [Mixed animation])
Add a point to the series after render time.
Parameters
options: Number|Array|Object
The point options. If options isa single number, a point with that y value is appended to the series.If it is an array, it will be interpreted as x and y values respectively, or inthe case of OHLC or candlestick, as [x, open, high, low, close]. If it is an object, advanced options as outlined under series.data are applied.
redraw: Boolean
Defaults to true. Whether to redraw the chart after the point is added. When adding more thanone point, it is highly recommended that the redraw option beset to false, and instead chart.redraw() is explicitly calledafter the adding of points is finished.
shift: Boolean
Defaults to false. When shift is true, one point is shifted off the start of the series as one is appended to the end. Use this option for live charts monitoring a value over time.
animation: Mixed
Defaults to true. When true, the graph will be animated with default animationoptions. The animation can also be a configuration object with properties durationand easing.
series.addPoint(acc, false, true);
/\ here's the problem, it should be false
Reference
http://api.highcharts.com/highstock#Series
Updated demo

Categories