Javascript / amcharts - dynamically control property value of amcharts - javascript

I am trying to mildly replicate what amcharts has done to their demo chart in this link ie. adding controls to change the graph's property. But I can't figure out how the value updating works in javascript. Here is my code:
HTML:
<body>
...
<div id="chartdiv" style="width=100%; height:400px;"></div>
<input type="range" min="0.1" max="1.0" value="0.5" step="0.01" id="mySlider">
...
</body>
Javascript/amCharts:
<script>
// data for amCharts
var chartData = [ {
"country": "USA",
"visits": 4252
}, {
"country": "China",
"visits": 1882
}];
// drawing amCharts using object-based method
AmCharts.ready( function() {
//var chart = AmCharts.makeChart("chartdiv");
var chart = new AmCharts.AmSerialChart();
chart.dataProvider = chartData;
chart.categoryField = "country";
var graph = new AmCharts.AmGraph();
graph.valueField = "visits";
graph.type = "column";
graph.fillAlphas = updateValue();
chart.addGraph( graph );
chart.write("chartdiv")
});
// here is my function to update value dynamically
function updateValue() {
val = document.getElementById("mySlider").value;
return val;
}
</script>
I want to update the opacity of the graph dynamically. How do I do that? This should be simple but I am quite new in javascript development.
EDIT: Updating with the final code which works
Javascript/amCharts:
<script>
...
// drawing amCharts using object-based method
AmCharts.ready( function() {
//var chart = AmCharts.makeChart("chartdiv");
var chart = new AmCharts.AmSerialChart();
chart.dataProvider = chartData;
chart.categoryField = "country";
var graph = new AmCharts.AmGraph();
graph.valueField = "visits";
graph.type = "column";
graph.fillAlphas = updateValue();
chart.addGraph( graph );
chart.write("chartdiv");
//add this code to add dynamic opacity control
//** "jquery.js" script needs to be linked **//
$('#mySlider').on('input change', function() {
//var target = chart;
//chart.startDuration = 0;
var target = chart.graphs[0]
target['fillAlphas'] = this.value;
chart.validateNow();
});
});
...
</script>

Try this code on change event of your input
jQuery('#mySlider').off().on('input change', function() {
var target = chart;
chart.startDuration = 0;
target = chart.graphs[0];
target['fillAlphas'] = this.value;
chart.validateNow();
});

Related

Add HTML Element On Top Of Amchart Instance

I can't find this in the documentation, but is it possible to add a custom div element on top of an Amchart Instance?
Such that:
<div class="container-fluid px-0 mx-0">
<div id="chartdiv"></div>
<ul>
<li>Thailand</li>
<li>Myanmar</li>
<li>Etc...</li>
</ul>
</div>
With the UL displaying at the bottom of the instance?
JS:
<script src="https://www.amcharts.com/lib/4/core.js"></script>
<script src="https://www.amcharts.com/lib/4/maps.js"></script>
<script src="https://www.amcharts.com/lib/4/geodata/worldUltra.js"></script>
<script src="https://www.amcharts.com/lib/4/themes/animated.js"></script>
<script>
am4core.useTheme(am4themes_animated);
var container = am4core.create("chartdiv", am4core.Container);
container.width = am4core.percent(100);
container.height = am4core.percent(100);
container.layout = "vertical";
// Create map instance
var chart = container.createChild(am4maps.MapChart);
// Set map definition
chart.geodata = am4geodata_worldUltra;
// Set projection
chart.projection = new am4maps.projections.Miller();
// Create map polygon series
var polygonSeries = chart.series.push(new am4maps.MapPolygonSeries());
// Exclude Antartica
polygonSeries.exclude = ["AQ"];
// Make map load polygon (like country names) data from GeoJSON
polygonSeries.useGeodata = true;
// Configure series
var polygonTemplate = polygonSeries.mapPolygons.template;
polygonTemplate.tooltipText = "{name}";
polygonTemplate.fill = am4core.color("#dcdcdc");
// Create hover state and set alternative fill color
var hs = polygonTemplate.states.create("hover");
hs.properties.fill = am4core.color("#a98239");
chart.events.on("ready", function(ev) {
chart.zoomToMapObject(polygonSeries.getPolygonById("TH"));
});
chart.zoomControl = new am4maps.ZoomControl();
chart.chartContainer.wheelable = false;
</script>
If I missed something in the docs, I apologize - hoping someone can point me in the right direction!
AmCharts is SVG based so everything in the chartdiv is controlled by the library and mostly contains SVG with a little bit of HTML, without any native options to include custom div objects. One potential workaround is to use a Label object and set its html property to include your HTML code. Note that this uses <foreignObject> to accomplish this, so you may need to be mindful of browser support (IE11, if that still matters).
Here's an example that creates a list on top of the chart
var label = chart.chartContainer.createChild(am4core.Label);
//label.isMeasured = false; //uncomment to make the label not adjust the rest of the chart elements to accommodate its placement
label.fontSize = 16;
label.x = am4core.percent(5);
label.horizontalCenter = "middle";
label.verticalCenter = "bottom";
label.html = "<ul><li>List item 1</li><li>List item 2</li></ul>";
label.toBack(); //move list to top of the chart area. See: https://www.amcharts.com/docs/v4/concepts/svg-engine/containers/#Ordering_elements
Demo:
// Create chart instance
var chart = am4core.create("chartdiv", am4charts.XYChart);
// Add data
chart.data = [{
"category": "Research",
"value": 450
}, {
"category": "Marketing",
"value": 1200
}, {
"category": "Distribution",
"value": 1850
}];
// Create axes
var categoryAxis = chart.xAxes.push(new am4charts.CategoryAxis());
categoryAxis.dataFields.category = "category";
categoryAxis.renderer.grid.template.location = 0;
//categoryAxis.renderer.minGridDistance = 30;
var valueAxis = chart.yAxes.push(new am4charts.ValueAxis());
// Create series
var series = chart.series.push(new am4charts.ColumnSeries());
series.dataFields.valueY = "value";
series.dataFields.categoryX = "category";
var label = chart.chartContainer.createChild(am4core.Label);
//label.isMeasured = false; //uncomment to make the label not adjust the rest of the chart elements to accommodate its placement
label.fontSize = 16;
label.x = am4core.percent(5);
label.horizontalCenter = "middle";
label.verticalCenter = "bottom";
label.html = "<ul><li>List item 1</li><li>List item 2</li></ul>";
label.toBack(); //move list to top of the chart area. See: https://www.amcharts.com/docs/v4/concepts/svg-engine/containers/#Ordering_elements
html, body { width: 100%; height: 100%; margin: 0;}
#chartdiv { width: 100%; height: 100%;}
<script src="//www.amcharts.com/lib/4/core.js"></script>
<script src="//www.amcharts.com/lib/4/charts.js"></script>
<div id="chartdiv"></div>

AMCharts How to color bullets by value?

I am working with amcharts and I tried to color bullets in the chart by the values they have. So I created an array in javascript and passed the values from the database into it. Green is just a value for testing.
var chartData = [
<?php
foreach($tmp as $row)
{
echo'{"Wahrscheinlichkeit":'.$row[3].',"Schaden":'.$row[4].',"value":1,"Beschreibung":"'.$row[2].'", "Color":"Green"},';
}
?>
];
Here I create the chart:
chart = new AmCharts.AmXYChart();
chart.dataProvider = chartData;
Here I draw the chart:
var graph = new AmCharts.AmGraph();
graph.valueField = "value"; // größe der Kugeln
graph.xField = "Wahrscheinlichkeit";
graph.yField = "Schaden";
graph.maxBulletSize=20;
graph.lineAlpha = 0;
graph.bullet = "circle";
graph.bulletColor= "[[Color]]";
graph.balloonText = "Wahrscheinlichkeit:<b>[[x]]</b> Schaden:<b>[[y]]</b><br>Beschreibung:<b> [[Beschreibung]]</b>"
chart.addGraph(graph);
At the point "bulletcolor" I try to get the color out of the array, but it doesn't work.
chart.write("chartdiv");
Looking forward getting tips and help from you
"bulletColor" can't reference fields in data like this.
Instead, please use "lineColorField":
http://docs.amcharts.com/3/javascriptcharts/AmGraph#lineColorField
I.e.:
var graph = new AmCharts.AmGraph();
graph.valueField = "value"; // größe der Kugeln
graph.xField = "Wahrscheinlichkeit";
graph.yField = "Schaden";
graph.maxBulletSize=20;
graph.lineAlpha = 0;
graph.bullet = "circle";
graph.lineColorField = "Color";
graph.balloonText = "Wahrscheinlichkeit:<b>[[x]]</b> Schaden:<b>[[y]]</b><br>Beschreibung:<b> [[Beschreibung]]</b>"
chart.addGraph(graph);

Amchart - Export to PNG file

I created an amchart for plotting time based area. I need to add an export to image option to this graph. Below shows my amchart code. What are the lines needed to add the export to image option to this graph
AmCharts.ready(function () {
// first we generate some random data
generateChartData();
// SERIAL CHART
chart = new AmCharts.AmSerialChart();
chart.pathToImages = "../amcharts/images/";
chart.dataProvider = chartData;
chart.categoryField = "date";
// data updated event will be fired when chart is first displayed,
// also when data will be updated. We'll use it to set some
// initial zoom
chart.addListener("dataUpdated", zoomChart);
// AXES
// Category
var categoryAxis = chart.categoryAxis;
categoryAxis.parseDates = true; // in order char to understand dates, we should set parseDates to true
categoryAxis.minPeriod = "mm"; // as we have data with minute interval, we have to set "mm" here.
categoryAxis.gridAlpha = 0.07;
categoryAxis.axisColor = "#DADADA";
// Value
var valueAxis = new AmCharts.ValueAxis();
valueAxis.gridAlpha = 0.07;
valueAxis.title = "Unique visitors";
chart.addValueAxis(valueAxis);
// GRAPH
var graph = new AmCharts.AmGraph();
graph.type = "line"; // try to change it to "column"
graph.title = "red line";
graph.valueField = "visits";
graph.lineAlpha = 1;
graph.lineColor = "#d1cf2a";
graph.fillAlphas = 0.3; // setting fillAlphas to > 0 value makes it area graph
chart.addGraph(graph);
// CURSOR
var chartCursor = new AmCharts.ChartCursor();
chartCursor.cursorPosition = "mouse";
chartCursor.categoryBalloonDateFormat = "JJ:NN, DD MMMM";
chart.addChartCursor(chartCursor);
// SCROLLBAR
var chartScrollbar = new AmCharts.ChartScrollbar();
chart.addChartScrollbar(chartScrollbar);
// WRITE
chart.write("chartdiv");
});
You should just be able to add the following before you write the chart to the DIV.
"exportConfig":{
"menuTop": 0,
menuItems: [{
textAlign: 'center',
icon: 'images/graph_export.png',
iconTitle: 'Save chart as an image',
onclick:function(){},
items: [
{title:'JPG', format:'jpg'},
{title:'PNG', format:'png'},
{title:'SVG', format:'svg'}
]
}]
}
This will give you a download icon on the graph to download in either JPG, PNG or SVG formats.
Try this code :
chart.export = {
enabled: true,
position: "bottom-right"
}
chart.initHC = false;
chart.validateNow();
And don't forget to include the needed export plugin!

amcharts showing value inside bar

I'm using amCharts, and i want to show values inside bar
This is how it looks at the moment:
and I want it to be like this:
This is my code to display chart:
AmCharts.ready(function() {
generateWidgetData('week');
// SERIAL CHART
chart = new AmCharts.AmSerialChart();
chart.dataProvider = graphData;
chart.categoryField = 'date';
chart.startDuration = 1;
chart.columnWidth = 0.60;
chart.dataDateFormat = 'YYYY-MM-DD';
chart.startEffect = 'easeInSine';
chart.stackType = 'regular';
// AXES
// category
var categoryAxis = chart.categoryAxis;
categoryAxis.parseDates = true;
categoryAxis.minPeriod = 'DD';
categoryAxis.plotAreaBorderAlpha = 0.01;
categoryAxis.labelRotation = 90;
categoryAxis.axisThickness = 0;
categoryAxis.stackType = 'regular';
categoryAxis.gridThickness = 0;
categoryAxis.inside = false;
//categoryAxis.gridPosition = 'start';
//categoryAxis.startDate = '2014-05-08';
// value
// in case you don't want to change default settings of value axis,
// you don't need to create it, as one value axis is created automatically.
// GRAPH
var graph = new AmCharts.AmGraph();
graph.maxColumns = 1;
graph.valueField = 'Self-entered';
graph.balloonText = '[[category]]: <b>[[value]]</b>';
graph.type = 'column';
graph.lineAlpha = 0;
graph.labelText = '[[value]]';
graph.fillAlphas = 0.8;
graph.stackType = 'regular';
chart.addGraph(graph);
graph.cornerRadiusTop = 8;
// CURSOR
var chartCursor = new AmCharts.ChartCursor();
chartCursor.cursorAlpha = 0;
chartCursor.zoomable = false;
chartCursor.categoryBalloonEnabled = false;
chart.addChartCursor(chartCursor);
chart.creditsPosition = 'top-right';
chart.write('stepschart');
});
Thanks in advance.
I fixed this so i will post answer, maybe it will help to someone
its really simple all you need to do is to add 2 lines of code:
graph.labelText = '[[value]]'; // this will insert values in labels
graph.labelPosition = 'inside'; // and with this we put our label inside bar
Hope this will help to someone who also need to do same thing

AmCharts - graphs connected by starting and ending points

I have multiple graphs per chart and for some unknown(to me) reason each graph is connected by the start and the end points of it e.g.
Simple question: How to remove it? I couldn't find anything in the documentation that controls it.
My code as follows:
lineChart = function(id, period) {
var chart, data = [];
var cData = chartData[id];
AmCharts.ready(function() {
for (item in cData) {
var i = cData[item];
data.push({
date: new Date(i.date),
impressions: i.impressions,
clicks: i.clicks,
conversions: i.conversions,
ctr: i.ctr,
profit: i.profit,
cost: i.cost,
revenue: i.revenue
});
}
chart = new AmCharts.AmSerialChart();
chart.dataProvider = data;
chart.categoryField = "date";
chart.balloon.color = "#000000";
// AXES
// category
var categoryAxis = chart.categoryAxis;
categoryAxis.fillAlpha = 1;
categoryAxis.fillColor = "#FAFAFA";
categoryAxis.gridAlpha = 0;
categoryAxis.axisAlpha = 0;
categoryAxis.minPeriod = period;
categoryAxis.parseDates = true;
categoryAxis.gridPosition = "start";
categoryAxis.position = "bottom";
// value
var valueAxis = new AmCharts.ValueAxis();
valueAxis.dashLength = 5;
valueAxis.axisAlpha = 0;
valueAxis.integersOnly = true;
valueAxis.gridCount = 10;
chart.addValueAxis(valueAxis);
// GRAPHS
// Impressions graph
var graph = new AmCharts.AmGraph();
graph.title = "Impressions";
graph.valueField = "impressions";
graph.balloonText = "[[title]]: [[value]]";
//graph.lineAlpha = 1;
graph.bullet = "round";
chart.addGraph(graph);
// Clicks graph
var graph = new AmCharts.AmGraph();
graph.title = "Clicks";
graph.valueField = "clicks";
graph.balloonText = "[[title]]: [[value]]";
graph.bullet = "round";
chart.addGraph(graph);
// Conversions graph
var graph = new AmCharts.AmGraph();
graph.title = "Conversion";
graph.valueField = "conversions";
graph.balloonText = "[[title]]: [[value]]";
graph.bullet = "round";
chart.addGraph(graph);
// LEGEND
var legend = new AmCharts.AmLegend();
legend.markerType = "circle";
chart.addLegend(legend);
var chartCursor = new AmCharts.ChartCursor();
chartCursor.cursorPosition = "mouse";
if(period == 'hh')
chartCursor.categoryBalloonDateFormat = "MMM DD, JJ:00";
chart.addChartCursor(chartCursor);
// WRITE
chart.write(id);
});
};
This looks like the data issue. Make sure your data points are strictly in consecutive ascending order.
To verify how your actual data looks like, add the second line below to your code. Then run your chart in Google Chrome with Console open (F12 then select Console tab)
chart.dataProvider = data;
console.debug(data);
Check the datapoints for irregularities. Especially the last two ones.
The problem was that each chart was rendered within it's own AmCharts.ready method. The documentation states that it's allowed, however it didn't work for me, therefore I wrapped all rendering within one ready method and the issue was fixed.

Categories