Dynamically changing legend AmCharts4 - javascript

The columns that have (maximum Additional Hedging) are sometimes on the chart and sometimes not this is determined on the dynamic data that can be changed constantly via a draggable bar above the chart.
I want to be able have the legend of the chart to remove these items when they aren't on the and bring them back when they are on the chart.
This is currently working on the AmCharts3 version of the chart but I am upgrading them.
var chart = am4core.create("fxExposureHedgingChart", am4charts.XYChart);
let title = chart.titles.create();
title.text = this.props.title;
title.fontSize = 25;
title.marginBottom = 30;
chart.data = this.props.dataProvider;
chart.dateFormatter.inputDateFormat = "yyyy-MM-dd";
chart.orderByField = "name"
var categoryAxis = chart.xAxes.push(new am4charts.CategoryAxis());
categoryAxis.dataFields.category = "category";
categoryAxis.title.text = "Time";
categoryAxis.renderer.startLocation = 0;
categoryAxis.renderer.cellStartLocation = 0.10;
categoryAxis.renderer.cellEndLocation = 0.90;
categoryAxis.renderer.labels.template.location = 0.5 ;
categoryAxis.renderer.labels.template.wrap = false;
categoryAxis.renderer.labels.template.truncate = false;
categoryAxis.renderer.minGridDistance = 30;
categoryAxis.layout = "horizontal";
// Create value axis
var valueAxis = chart.yAxes.push(new am4charts.ValueAxis());
valueAxis.title.text = "Amount " + this.state.displayCurrency;
valueAxis.max = 140000;
valueAxis.min = 0;
let valueAxis2 = chart.yAxes.push(new am4charts.ValueAxis());
valueAxis2.title.text = "Rate";
valueAxis2.renderer.opposite = true;
valueAxis2.min = 1.1000;
valueAxis2.max = 1.4500;
let createColumnSeries = () => {
var series = chart.series.push(new am4charts.ColumnSeries());
series.dataFields.valueY = "exposure";
series.dataFields.categoryX = "category";
series.name = "Forecasted Cashflows";
series.yAxis = valueAxis;
series.columns.template.width = am4core.percent(85);
series.stacked = false;
series.tooltip.dy = -8;
series.tooltip.pointerOrientation = "vertical";
var columnTemplate = series.columns.template;
columnTemplate.column.fillOpacity = 0.8;
columnTemplate.tooltipText = "{name} ({category}): {valueY}";
columnTemplate.tooltipY = 0;
var columnHoverState = columnTemplate.column.states.create("hover");
columnHoverState.properties.fillOpacity = 1;
columnHoverState.properties.cornerRadiusTopLeft = 35;
columnHoverState.properties.cornerRadiusTopRight = 35;
return series;
}
let createLineSeries1 = () => {
var series = chart.series.push(new am4charts.LineSeries());
series.dataFields.valueY = "achieveableRate";
series.dataFields.categoryX = "category";
series.name = "Achieveable Rate";
series.tooltipText = "{valueY.value}";
series.strokeWidth = 2;
series.yAxis = valueAxis2;
let bullet = series.bullets.push(new am4charts.Bullet());
let square = bullet.createChild(am4core.Rectangle);
square.width = 5;
square.height = 5;
square.horizontalCenter = "middle";
square.verticalCenter = "middle";
series.bullets.getIndex(0).tooltipText = "{name}: {valueY}";
return series;
}
let getDealGraphInfo = (classIds,data) =>{
let maxHedgingClassIDs = classIds.map( id => (data.reduce((accum, row) => accum+ (row["maxAmount_"+id]),0)) > 0 ? id: null);
let maxAmounts = maxHedgingClassIDs.map((id, index) => {
if(id === null){} else {
let HedgingSeries = chart.series.push(new am4charts.ColumnSeries());
HedgingSeries.dataFields.valueY = "maxAmount_" + id;
HedgingSeries.dataFields.categoryX = "category";
HedgingSeries.name = classIDtoDisplayName(id).replace(/FX\s/,"") + " (Maximum Additional Hedging)";
HedgingSeries.tooltip.dy = -8;
HedgingSeries.tooltip.pointerOrientation = "vertical";
HedgingSeries.columns.template.width = am4core.percent(70);
HedgingSeries.id = classIDtoDisplayName(id).replace(/\s/g,"").toLowerCase() + "_maxAmount";
HedgingSeries.stacked = true;
var columnTemplate = HedgingSeries.columns.template;
columnTemplate.column.fillOpacity = 0.8;
columnTemplate.tooltipText = HedgingSeries.name;
columnTemplate.tooltipY = 0;
}}).filter(c => c);
return classIds.map((id, index) => {
let Series = chart.series.push(new am4charts.ColumnSeries());
Series.dataFields.valueY = "amount_" + id;
Series.dataFields.categoryX = "category";
Series.name = classIDtoDisplayName(id).replace(/FX\s/,"");
Series.tooltip.dy = -8;
Series.tooltip.pointerOrientation = "vertical";
Series.columns.template.width = am4core.percent(70);
Series.id = classIDtoDisplayName(id).replace(/\s/g,"").toLowerCase();
Series.strokewidth = 1;
Series.stacked = true;
var columnTemplate = Series.columns.template;
columnTemplate.column.fillOpacity = 0.8;
columnTemplate.tooltipText = Series.name;
columnTemplate.tooltipY = 0;
return Series;
}).concat(maxAmounts).sort((a,b) => (a.name < b.name ? -1:1));
}
let budgetRateName = getBudgetRateName(this.props.budgetRate);
getDealGraphInfo(this.props.dealClassIds,this.state.data).concat(createColumnSeries(),
createLineSeries1(),
createLineSeries2(),
createLineSeries3(),
createLineSeries4(budgetRateName)
).sort((a,b) => (a.name < b.name ? -1:1));
chart.legend = new am4charts.Legend();
chart.legend.itemContainers.template.paddingTop = 5;
chart.legend.itemContainers.template.paddingBottom = 5;
chart.legend.labels.template.wrap = true;
chart.legend.labels.template.maxWidth = 350;
chart.legend.labels.template.truncate = true;
chart.legend.useDefaultMarker = true;
chart.exporting.menu = new am4core.ExportMenu();
var plugin = chart.plugins.push(new am4plugins_annotation.Annotation());
var markerTemplate = chart.legend.markers.template
markerTemplate.width = 10;
markerTemplate.height = 10;
this.setState({chart: chart})
}
componentDidUpdate(oldProps, prevState){
if (oldProps.dataProvider !== this.props.dataProvider){
this.state.chart.data = this.props.dataProvider;
}
}
componentWillUnmount() {
if (this.chart) {
this.chart.dispose();
}
}
getDealGraphInfo are the columns that are being added/removed. Note, the object always has these columns but when they have no value it is set to "null" otherwise it has a value.
When I drag the bar above the chart I am using componentDidUpdate to change the data on the chart. So I believe the solution could have something to do in here.

I have found a temp fix where in componentDidUpdate I dispose the chart and recreate the whole chart when I receive new props. But this is very laggy when using the slider. I would prefer to just have the legend/data in the chart update, than needing to recreate the chart every time.

Related

Amcharts 4: Ghost bullets/ duplicate bullets on chart reload

Bug description
Hello.
I just got this error where duplicate/ ghost bullets are created every time my chart reloads when there's is new data. I tried everything I could by doing a deep dive into the documentation but I couldn't get rid of these ghost bullets. I'm not sure if there's any bug in the system or if I’m doing something wrong. Any help would be highly appreciated.
Thank you,
Here's the code I'm using to develop the chart:
import React, { Component } from "react";
import { isEqual } from "lodash";
import * as am4core from "#amcharts/amcharts4/core";
import * as am4charts from "#amcharts/amcharts4/charts";
import am4themes_animated from "#amcharts/amcharts4/themes/animated";
import "./index.scss";
am4core.useTheme(am4themes_animated);
am4core.options.onlyShowOnViewport = true;
am4core.options.queue = true;
export default class index extends Component {
componentDidMount() {
let chart = am4core.create(this.props.name, am4charts.XYChart);
chart.colors.list = [
am4core.color("#FFFDAD"),
am4core.color("##F4A460"),
am4core.color("#75B9FF"),
am4core.color("#FF94BA"),
];
chart.dateFormatter.dateFormat = "yyyy-MM-dd";
chart.dateFormatter.utc = false;
chart.paddingRight = 20;
let chartEvents = this.props.chartEvents || [];
chart.data = chartEvents;
chart.legend = new am4charts.Legend();
chart.legend.labels.template.fill = am4core.color("#FFFFFF");
chart.legend.labels.template.propertyFields.fill = "stroke";
chart.legend.position = "top";
chart.legend.itemContainers.template.paddingTop = 5;
chart.legend.itemContainers.template.paddingBottom = 5;
chart.legend.fontSize = 15;
chart.legend.marginBottom = 25;
let marker = chart.legend.markers.template.children.getIndex(0);
marker.cornerRadius(12, 12, 12, 12);
marker.strokeWidth = 5;
let markerTemplate = chart.legend.markers.template;
markerTemplate.width = 10;
markerTemplate.height = 10;
let dateAxis = chart.xAxes.push(new am4charts.DateAxis());
dateAxis.renderer.labels.template.fill = am4core.color("#FFFFFF");
dateAxis.title.text = "Time";
dateAxis.title.fill = am4core.color("#FFFFFF");
dateAxis.renderer.grid.template.location = 0;
dateAxis.fontSize = 15;
dateAxis.skipEmptyPeriods = true;
dateAxis.renderer.grid.template.disabled = true;
dateAxis.keepSelection = true;
dateAxis.groupData = true;
dateAxis.dateFormats.setKey("day", "yyyy-MM-dd");
dateAxis.periodChangeDateFormats.setKey("day", "yyyy-MM-dd");
dateAxis.groupIntervals.setAll([{ timeUnit: "minute", count: 15 }]);
dateAxis.minZoomCount = 5;
dateAxis.showOnInit = false;
let valueAxis = chart.yAxes.push(new am4charts.ValueAxis());
valueAxis.renderer.labels.template.fill = am4core.color("#FFFFFF");
valueAxis.tooltip.disabled = true;
valueAxis.renderer.minWidth = 35;
valueAxis.title.text = "Units";
valueAxis.fontSize = 15;
valueAxis.title.fill = am4core.color("#FFFFFF");
valueAxis.min = 0;
valueAxis.renderer.grid.template.disabled = false;
let series1 = chart.series.push(new am4charts.LineSeries());
series1.name = "Series1";
series1.tooltipText = this.renderTooltip("series1");
series1.dataFields.dateX = "timestamp";
series1.dataFields.valueY = "series1";
series1.tooltip.getFillFromObject = false;
series1.tooltip.background.fill = am4core.color("#FFFDAD");
series1.tooltip.label.fill = am4core.color("#000");
series1.stroke = am4core.color("#FFFDAD");
series1.strokeWidth = 2;
series1.connect = false;
series1.showOnInit = false;
let series2 = chart.series.push(new am4charts.LineSeries());
series2.name = "Series2";
series2.tooltipText = this.renderTooltip("series2");
series2.dataFields.dateX = "timestamp";
series2.dataFields.valueY = "series2";
series2.tooltip.getFillFromObject = false;
series2.tooltip.background.fill = am4core.color("#F4A460");
series2.tooltip.label.fill = am4core.color("#000");
series2.stroke = am4core.color("#F4A460");
series2.strokeWidth = 2;
series2.connect = false;
series2.showOnInit = false;
let series3 = chart.series.push(new am4charts.LineSeries());
series3.name = "series3";
series3.tooltipText = `Name: [bold]Series3[/]
Time : {timestamp.formatDate('yyyy-MM-dd HH:mm:ss')} `;
series3.dataFields.dateX = "timestamp";
series3.dataFields.valueY = "series3";
series3.strokeOpacity = 0;
series3.sequencedInterpolation = true;
series3.tooltip.background.fill = am4core.color("#75B9FF");
series3.minBulletDistance = 15;
series3.showOnInit = false;
series3.autoDispose = true;
let bullet = series3.bullets.push(new am4charts.Bullet());
bullet.isDynamic = true;
let triangle = bullet.createChild(am4core.Triangle);
triangle.width = 11;
triangle.height = 11;
triangle.dy = 5;
triangle.direction = "bottom";
triangle.propertyFields.fill = am4core.color("#75B9FF");
triangle.propertyFields.fillOpacity = 1;
triangle.fillOpacity = 1;
triangle.strokeWidth = 1;
triangle.horizontalCenter = "middle";
triangle.verticalCenter = "bottom";
let hoverState = bullet.states.create("hover");
hoverState.properties.scale = 1.7;
let series4 = chart.series.push(new am4charts.LineSeries());
series4.name = "series4";
series4.tooltipText = `Name: [bold]series4[/]
Time : {timestamp.formatDate('yyyy-MM-dd HH:mm:ss')}`;
series4.dataFields.dateX = "timestamp";
series4.dataFields.valueY = "series4";
series4.strokeOpacity = 0;
series4.sequencedInterpolation = true;
series4.tooltip.background.fill = am4core.color("#FF94BA");
series4.minBulletDistance = 15;
series4.showOnInit = false;
series4.autoDispose = true;
let bullet01 = series4.bullets.push(new am4core.Circle());
bullet01.radius = 5;
bullet01.propertyFields.fill = am4core.color("#FF94BA");
bullet01.fillOpacity = 1;
bullet01.isDynamic = true;
let hoverState1 = bullet01.states.create("hover");
hoverState1.properties.scale = 1.7;
let range = dateAxis.axisRanges.create();
range.date = new Date();
range.grid.stroke = am4core.color("red");
range.grid.strokeWidth = 1;
range.grid.strokeOpacity = 0.5;
chart.cursor = new am4charts.XYCursor();
chart.showOnInit = true;
chart.zoomOutButton.dom.addEventListener("click", this.resetDateSelector);
chart.maskBullets = true;
chart.events.on("shown", () => {
dateAxis.zoomToDates(this.setStartTime(7), this.setEndTime(2), false);
});
this.chart = chart;
this.dateAxis = dateAxis;
}
componentDidUpdate(oldProps) {
if (
!isEqual(
oldProps.chartEvents,
this.props.chartEvents
) &&
typeof this.props.chartEvents === "object" &&
this.props.chartEvents.length !== 0
) {
this.chart.data = this.props.chartEvents;
this.chart.reinit();
}
}
componentWillUnmount() {
if (this.chart) {
this.chart.dispose();
}
}
renderTooltip = (name) => {
return `{name}: [bold]{${name}}[/]
Time: {timestamp.formatDate('yyyy-MM-dd HH:mm:ss')}[/]`;
};
setStartTime = (days) => {
let currentDate = new Date();
let pastTime = currentDate.setDate(currentDate.getDate() - days);
return pastTime;
};
setEndTime = (days) => {
let currentDate = new Date();
let futureTime = currentDate.setDate(currentDate.getDate() + days);
return futureTime;
};
resetDateSelector = () => {
this.dateAxis.zoomToDates(this.setStartTime(7), this.setEndTime(2));
};
render() {
return (
<div
id={this.props.name}
style={{ width: "100%", minHeight: "550px" }}
></div>
);
}
}
Environment
Amcharts version: 4.9.23
React version: 16.12.0
Chrome browser version: 83.0.4103.61
I was able to fix this issue by using the following code:
for (const series of chart.series) { series.bulletsContainer.disposeChildren() }
before setting
chart.data = data;
I was able to get this solution from the following Amcharts4 bug issue #1908 thread:
https://github.com/amcharts/amcharts4/issues/1908

AmCharts 4 Breaking when a series has no value

I have a graph with two "series", only when one has value and the other does not, it breaks and has no background. How to fix it? I've tried several posts from various sites, videos and also read the documentation a lot. No example seems to work, so I don't know exactly what to do. If it has value it looks like it looks normal.
Javascript
function initChartVendas() {
am4core.useTheme(am4themes_animated);
let chart = am4core.create(this.chartElement.nativeElement, am4charts.XYChart);
chart.data = this.generatechartData();
chart.numberFormatter.numberFormat = "'R$ ' #,###.##";
// Create axes
let dateAxis = chart.xAxes.push(new am4charts.DateAxis());
dateAxis.startLocation = 0.5;
dateAxis.endLocation = 0.5;
dateAxis.extraMax = null;
dateAxis.extraMin = null;
dateAxis.dateFormats.setKey('day', 'dd');
// Create value axis
let valueAxis = chart.yAxes.push(new am4charts.ValueAxis());
valueAxis.baseValue = 900;
// Create series
let series = chart.series.push(new am4charts.LineSeries());
series.name = 'Pagos ';
series.dataFields.valueY = 'valor';
series.dataFields.dateX = 'dia';
series.strokeWidth = 3;
series.tooltipText = '{valueY.value}';
series.fillOpacity = 0.1;
series.tensionX = 0.8;
series.tensionY = 1;
series.fill = am4core.color('#5770ef');
series.stroke = am4core.color('#5867dd');
// Create series 2
if (this.dataCancelados) {
let seriesCancelados = chart.series.push(new am4charts.LineSeries());
seriesCancelados.name = 'Cancelados ';
seriesCancelados.dataFields.valueY = 'cancelado';
seriesCancelados.dataFields.dateX = 'dia';
seriesCancelados.strokeWidth = 3;
seriesCancelados.tooltipText = '{valueY.value}';
seriesCancelados.fillOpacity = 0.1;
seriesCancelados.tensionX = 0.8;
seriesCancelados.tensionY = 1;
seriesCancelados.fill = am4core.color('#f96191');
seriesCancelados.stroke = am4core.color('#fd397a');
}
// Add cursor
chart.cursor = new am4charts.XYCursor();
chart.cursor.behavior = 'none';
series.tooltip.getFillFromObject = false;
series.tooltip.adapter.add('x', (x, target) => {
// #ts-ignore
const valueY = series.tooltip.tooltipDataItem.valueY;
if (valueY < 0) {
series.tooltip.background.fill = chart.colors.getIndex(4);
} else {
series.tooltip.background.fill = am4core.color('#5770ef');
}
return x;
});
if (this.dataCancelados) {
chart.legend = new am4charts.Legend();
}
}
Image 1
Image 2
I found the solution the dates should be ordered. Before they were not, for example, the 20th came before the 16th. That's why the problem. My ordering solution is this (it only matters the day)
chartData.sort((v1, v2) => (v1.dia.getDate() > v2.dia.getDate() ? 1 : -1));

easyui rowdata how to get value of column by index of the column but not field?

I don't want the '0' when the "指标4名称" is null.
below is my js code:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
first[12+4*i]['field'] = 'fxzb'+(i+1)+'_mc';
first[12+4*i]['title'] = '指标'+(i+1)+'名称';
first[12+4*i]['align'] = 'center';
first[12+4*i]['width'] = 150;
first[13+4*i] = new Array();
first[13+4*i]['field'] = 'fxzb'+(i+1)+'_ysz';
first[13+4*i]['title'] = '指标'+(i+1)+'运算值';
first[13+4*i]['align'] = 'center';
first[14+4*i] = new Array();
first[14+4*i]['field'] = 'fxzb'+(i+1)+'_df';
first[14+4*i]['title'] = '指标'+(i+1)+'得分';
first[14+4*i]['align'] = 'center';
first[14+4*i]['formatter'] = function(value, rowdata, rowindex){
if(row[12+4*i] == ""||rowdata[12+4*i]==null){
return null;
}else{
return value;
}
};
first[15+4*i] = new Array();
first[15+4*i]['field'] = 'fxzb'+(i+1)+'_ms';
first[15+4*i]['title'] = '指标'+(i+1)+'风险描述';
first[15+4*i]['align'] = 'center';
I just want to know how to get the value of 'fxzb'+(i+1)+'_mc',because I couldn't get it by rowdata.field.
I didn't get the value of 'fxzb'+(i+1)+'_mc',but I figured my questions out.
code as below:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
var flag;
first[12+4*i]['field'] = 'fxzb'+(i+1)+'_mc';
first[12+4*i]['title'] = '指标'+(i+1)+'名称';
first[12+4*i]['align'] = 'center';
first[12+4*i]['width'] = 150;
first[12+4*i]['formatter'] = function(value,rowdata,rowindex){
if(value=="" || value==null){
flag = true;
}else{
flag = false;
}
retrun value;
}
first[13+4*i] = new Array();
first[13+4*i]['field'] = 'fxzb'+(i+1)+'_ysz';
first[13+4*i]['title'] = '指标'+(i+1)+'运算值';
first[13+4*i]['align'] = 'center';
first[14+4*i] = new Array();
first[14+4*i]['field'] = 'fxzb'+(i+1)+'_df';
first[14+4*i]['title'] = '指标'+(i+1)+'得分';
first[14+4*i]['align'] = 'center';
first[14+4*i]['formatter'] = function(value, rowdata, rowindex){
if(flag){
return null;
}else{
return value;
}
};
first[15+4*i] = new Array();
first[15+4*i]['field'] = 'fxzb'+(i+1)+'_ms';
first[15+4*i]['title'] = '指标'+(i+1)+'风险描述';
first[15+4*i]['align'] = 'center';

Remove bank holidays from X Axis by amchart

I have data by date like this there is no 2017/07/17,2017/07/16,2017/07/15
because they are bank holidays.
chartData = new Array();
chartData[0] = new Array();
chartData[0].closePrice = 1207;
chartData[0].date = new Date("2017/07/12");
chartData[1] = new Array();
chartData[1].closePrice = 1227;
chartData[1].date = new Date("2017/07/13");
chartData[2] = new Array();
chartData[2].closePrice = 1216;
chartData[2].date = new Date("2017/07/14");
chartData[3] = new Array();
chartData[3].closePrice = 1234;
chartData[3].date = new Date("2017/07/18");
I use this chartData as dataProvider for making graph.
var dataSet = new AmCharts.DataSet();
dataSet.dataProvider = chartData;
dataSet.categoryField = "date";
chart.dataSets = [dataSet];
var stockPanel = new AmCharts.StockPanel();
stockPanel.title = "Stock Main";
stockPanel.id = "stockPanel";
stockPanel.showCategoryAxis = false;
stockPanel.recalculateToPercents = "never";
var valueAxis = new AmCharts.ValueAxis();
valueAxis.dashLength = 5;
stockPanel.addValueAxis(valueAxis);
stockPanel.categoryAxis.dashLength = 5;
stockPanel.categoryAxis.equalSpacing = true; // it doesn't work ....
var graph = new AmCharts.StockGraph();
graph.type = "line";
graph.valueField = "closePrice";
stockPanel.addStockGraph(graph);
however 2017/07/15,2017/07/16 2017/07/16 are drawn on X axis , even there are no data.
Even .equalSpacing looks in vain.
How can I remove this???
You have to set equalSpacing in the categoryAxesSettings property in the stock chart for it to work.
//object-based setup
chart.categoryAxesSettings = new AmCharts.CategoryAxesSettings();
chart.categoryAxesSettings.equalSpacing = true;
//makeChart version
AmCharts.makeChart("chartdiv", {
// ...
"categoryAxesSettings": {
"equalSpacing": true
},
// ...
});
Demo

Load amchart on page

My code looks like:
var check = parametrTable.length -1;
var data = [];
$.each(parametrTable, function(i, x) { // NOTE: x = parametrTable[i]
$.getJSON("myurlwithparametr", function(json) {
$.each(json, function(j, d) {
data[j] = data[j] || {};
data[j]["count" + i] = d.count;
if (i == 0) {
data[j].category = d.column;
}
});
if(i == check){
loadChart(data);
}
});
});
This part generate data from my amchart, next if 'i' == 'check' (end of .each loop) i send generate data to function 'loadChart' with parametr 'data'.
Code for my function:
AmCharts.ready(function() {
chart = new AmCharts.AmSerialChart();
chart.dataProvider = data;
chart.categoryField = "category";
chart.startDuration = 1;
chart.type = "serial";
var categoryAxis = chart.categoryAxis;
categoryAxis.labelRotation = 90;
categoryAxis.axisAlpha = 1;
categoryAxis.insie = true;
categoryAxis.gridPosition = "start";
var valueAxis = new AmCharts.ValueAxis();
valueAxis.title = "title";
valueAxis.axisAlpha = 1;
chart.addValueAxis(valueAxis);
for (i=0;i<data.length;++i) {
var graph = new AmCharts.AmGraph();
graph.valueField = "count"+i+"";
graph.balloonText = "[[value]]";
graph.bullet = "round";
graph.type = "smoothedLine";
graph.lineAlpha = 1;
graph.connect = true;
graph.lineThickness = '2';
//graph.fillAlphas = 1;
chart.addGraph(graph);
}
chart.write('chartdiv');
});
On my page i have div with id = 'chartdiv'. When I check in the function the values in the table (data) its look ok, but my chart does not regenerate. :( When I skip
AmCharts.ready(function() {
chart is generated, but not all the values. Any sugestions?
It's hard to tell without seeing your actual data, but it seems that the issue is how you crate your graphs. Right now you are creating a separate graph for each data point in your data. That does not seem right. You should create for each item in parametrTable:
for (i=0;i<=check;++i) {
var graph = new AmCharts.AmGraph();
graph.valueField = "count"+i+"";
graph.balloonText = "[[value]]";
graph.bullet = "round";
graph.type = "smoothedLine";
graph.lineAlpha = 1;
graph.connect = true;
graph.lineThickness = '2';
//graph.fillAlphas = 1;
chart.addGraph(graph);
}
Additionally, jQuery AJAX calls are asynchronous. Meaning that the your .each() cycle completes before actual data is loaded.
You need to keep separate iterator to keep track of number of loaded items. I.e.:
var check = parametrTable.length -1;
var loaded = 0;
var data = [];
$.each(parametrTable, function(i, x) { // NOTE: x = parametrTable[i]
$.getJSON("myurlwithparametr", function(json) {
loaded++;
$.each(json, function(j, d) {
data[j] = data[j] || {};
data[j]["count" + i] = d.count;
if (i == 0) {
data[j].category = d.column;
}
});
if(loaded == check){
loadChart(data);
}
});
});

Categories