AmCharts: custom button to hide/show graph - amcharts

I would like to have my own buttons to hide/show lines on a linear graph.
The legend is fine, but I want my own HTML/CSS.
Is there a way to do this?
Attaching the hide/show event maybe?
Thank you

You can call the showGraph and hideGraph methods from your buttons' events. Since they take the graph instance, you'll want to have access to the chart to pass in the desired graph instance either by accessing the graphs array directly or calling getGraphById if you set ids for your graphs, then check the graph's hidden property to know when to call showGraph or hideGraph
Assuming you have the graph index in your button's markup like <button data-graph-index="0">Toggle first graph</button>, you could do something like this:
button.addEventListener('click', function(e) {
var graph = chart.graphs[e.currentTarget.dataset.graphIndex];
if (graph.hidden) {
chart.showGraph(graph);
}
else {
chart.hideGraph(graph);
}
});
Here's a demo:
var chart;
Array.prototype.forEach.call(
document.querySelectorAll('.toggle-graph'),
function (button) {
button.addEventListener('click', function(e) {
var graph = chart.graphs[e.currentTarget.dataset.graphIndex];
if (graph.hidden) {
chart.showGraph(graph);
}
else {
chart.hideGraph(graph);
}
});
}
);
chart = AmCharts.makeChart("chartdiv", {
"type": "serial",
"theme": "light",
"dataProvider": [{
"year": 1994,
"cars": 1587,
"motorcycles": 650,
"bicycles": 121
}, {
"year": 1995,
"cars": 1567,
"motorcycles": 683,
"bicycles": 146
}, {
"year": 1996,
"cars": 1617,
"motorcycles": 691,
"bicycles": 138
}, {
"year": 1997,
"cars": 1630,
"motorcycles": 642,
"bicycles": 127
}, {
"year": 1998,
"cars": 1660,
"motorcycles": 699,
"bicycles": 105
}, {
"year": 1999,
"cars": 1683,
"motorcycles": 721,
"bicycles": 109
}, {
"year": 2000,
"cars": 1691,
"motorcycles": 737,
"bicycles": 112
}, {
"year": 2001,
"cars": 1298,
"motorcycles": 680,
"bicycles": 101
}, {
"year": 2002,
"cars": 1275,
"motorcycles": 664,
"bicycles": 97
}, {
"year": 2003,
"cars": 1246,
"motorcycles": 648,
"bicycles": 93
}, {
"year": 2004,
"cars": 1318,
"motorcycles": 697,
"bicycles": 111
}, {
"year": 2005,
"cars": 1213,
"motorcycles": 633,
"bicycles": 87
}, {
"year": 2006,
"cars": 1199,
"motorcycles": 621,
"bicycles": 79
}, {
"year": 2007,
"cars": 1110,
"motorcycles": 210,
"bicycles": 81
}, {
"year": 2008,
"cars": 1165,
"motorcycles": 232,
"bicycles": 75
}, {
"year": 2009,
"cars": 1145,
"motorcycles": 219,
"bicycles": 88
}, {
"year": 2010,
"cars": 1163,
"motorcycles": 201,
"bicycles": 82
}, {
"year": 2011,
"cars": 1180,
"motorcycles": 285,
"bicycles": 87
}, {
"year": 2012,
"cars": 1159,
"motorcycles": 277,
"bicycles": 71
}],
"valueAxes": [{
"gridAlpha": 0.07,
"position": "left",
"title": "Traffic incidents"
}],
"graphs": [{
"title": "Cars",
"valueField": "cars"
}, {
"title": "Motorcycles",
"valueField": "motorcycles"
}, {
"title": "Bicycles",
"valueField": "bicycles"
}],
"chartCursor": {
"cursorAlpha": 0
},
"categoryField": "year",
"categoryAxis": {
"startOnAxis": true,
"axisColor": "#DADADA",
"gridAlpha": 0.07,
"title": "Year"
},
"export": {
"enabled": true
}
});
<script type="text/javascript" src="//www.amcharts.com/lib/3/amcharts.js"></script>
<script type="text/javascript" src="//www.amcharts.com/lib/3/serial.js"></script>
<button class="toggle-graph" data-graph-index="0">Toggle first graph</button>
<button class="toggle-graph" data-graph-index="1">Toggle second graph</button>
<button class="toggle-graph" data-graph-index="1">Toggle third graph</button>
<div id="chartdiv" style="width: 100%; height: 300px;"></div>

Not sure if its a version issue or a different way I was using the api, but the accepted answer hadn't worked for me. In fact chart.graphs itself wasn't defined.
All I was used was
chart.show()
and
chart.hide()
Background...
const [chart, setChart] = useState(null)
...
let newChart = root.container.children.push(
am5xy.XYChart.new(root, {
panX: false,
panY: false,
wheelX: 'none',
wheelY: 'none',
layout: root.verticalLayout,
})
setChart(newChart)
I also had some tooltips and modal dialogue (to show when the chart is empty)
const hideChartTooltip = () => {
const tooltip = chart.series.getIndex(0).get('tooltip')
if (tooltip) {
tooltip.set('forceHidden', true)
tooltip.hide()
}
}
useEffect(() => {
if (!chart) {
console.log('show/hide graph no-op')
return
}
console.log(`chart view mode : ${isChartView}`)
if (isChartView) {
chart.show()
}
else {
console.log('hiding the graph... ')
hideChartTooltip()
chart.hide()
}
}, [isChartView])
Ref: Sprite - hide
Inheritance hierarchy...
Chart <- Container <- Sprite

Related

How to render default values from Django Serializer for charting purposes?

I'm using Django Rest to aggregate some data for my front end to render (through Chart.js)
Say I want to have a chart with the months (Jan-Dec) on the x-axis and total_cost values on the y-axis. How can I make sure to always spit out all 12 months and provide "0" for the y-axis if no value for that month is found?
E.g, this serialized data from Django rest is missing values for November and December, but I still need those labels for Chart JS to properly render
[
{
"month": "2020-01-01",
"total_cost": "199.00"
},
{
"month": "2020-02-01",
"total_cost": "222.00"
},
{
"month": "2020-03-01",
"total_cost": "399.00"
},
{
"month": "2020-04-01",
"total_cost": "414.00"
},
{
"month": "2020-05-01",
"total_cost": "555.00"
},
{
"month": "2020-06-01",
"total_cost": "615.00"
},
{
"month": "2020-07-01",
"total_cost": "700.00"
},
{
"month": "2020-08-01",
"total_cost": "913.00"
},
{
"month": "2020-09-01",
"total_cost": "552.00"
},
{
"month": "2020-10-01",
"total_cost": "1000.00"
}
]
Perhaps this is a matter for the frontend rather than the backend?
If it helps, my django query looks like this:
queryset = Expense.object.annotate(month=TruncMonth('expense_date'))
.values('month')
.annotate(total_cost=Sum('cost'))
.values('month', 'total_cost')
.order_by('month')
As you correctly guessed, this is best handled in the the frontend rather than in the backend.
You can define your x-axis as a time cartesian axis that accepts the data of your dataset as individual points through objects containing x and y properties each. Given the base data present in an array named baseData, such data can be created through Array.map() as follows:
baseData.map(o => ({ x: o.month, y: Number(o.total_cost) }))
To make sure, all 12 months are included in the chart, you'll further have to define ticks.min and ticks.max options on the x-axis.
ticks: {
min: '2020-01',
max: '2020-12'
}
Please take a look at the following runnable code and see how it works.
Note that Chart.js internally uses Moment.js for the functionality of the time axis. Therefore you should use the bundled version of Chart.js that includes Moment.js in a single file.
const baseData = [
{ "month": "2020-01-01", "total_cost": "199.00" },
{ "month": "2020-02-01", "total_cost": "222.00" },
{ "month": "2020-03-01", "total_cost": "399.00" },
{ "month": "2020-04-01", "total_cost": "414.00" },
{ "month": "2020-05-01", "total_cost": "555.00" },
{ "month": "2020-06-01", "total_cost": "615.00" },
{ "month": "2020-07-01", "total_cost": "700.00" },
{ "month": "2020-08-01", "total_cost": "913.00" },
{ "month": "2020-09-01", "total_cost": "552.00" },
{ "month": "2020-10-01", "total_cost": "1000.00" }
];
new Chart(document.getElementById('myChart'), {
type: 'line',
data: {
datasets: [{
label: 'My Dataset',
data: baseData.map(o => ({ x: o.month, y: Number(o.total_cost) })),
fill: false,
backgroundColor: 'green',
borderColor: 'green'
}]
},
options: {
responsive: true,
scales: {
xAxes: [{
type: 'time',
time: {
unit: 'month',
tooltipFormat: 'MMM YYYY'
},
ticks: {
min: '2020-01',
max: '2020-12'
}
}],
yAxes: [{
ticks: {
beginAtZero: true,
stepSize: 200
}
}]
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.bundle.min.js"></script>
<canvas id="myChart" height="90"></canvas>

loading json data How to show clustered bar charts in dynamic graphs

Updated
Can you possible graphs value dynamic.
Below code pass a static value but i get dynamic code graphs.
Example: resultx get 3-4 subcategory i every time define graphs value.
var processedChartData = resultx.map(function(rawDataElement) {
var newDataElement = { "category": rawDataElement.category };
rawDataElement.data.forEach(function(nestedElement, index) {
newDataElement["value" + index] = nestedElement.value;
newDataElement["subcategory" + index] = nestedElement.subcategory
});
return newDataElement;
});
AmCharts.makeChart(id, {
"type": "serial",
"theme": "light",
"categoryField": "category",
"rotate": false,
"startDuration": 0,
"categoryAxis": {
"gridPosition": "start",
"position": "left"
},
"graphs": [{
"fillAlphas": 0.9,
"lineAlpha": 0.2,
"title": "2004",
"type": "column",
"balloonText": "[[subcategory0]]: [[value]]",
"valueField": "value0"
}, {
"fillAlphas": 0.9,
"lineAlpha": 0.2,
"title": "2005",
"type": "column",
"balloonText": "[[subcategory1]]: [[value]]",
"valueField": "value1"
},
{
"fillAlphas": 0.9,
"lineAlpha": 0.2,
"title": "2005",
"type": "column",
"balloonText": "[[subcategory2]]: [[value]]",
"valueField": "value2",
}],
"guides": [],
"allLabels": [],
"balloon": {},
"titles": [],
"dataProvider": processedChartData,
"export": {
"enabled":false
}
});
Original question:
Clustered bar charts Array inside key how to display multiple bar charts.
My json below:
[
{
"0":
{
"package_sold":"88",
"vSectorName":"Meat"
},
"country":"France"
},
{
"0":
{
"package_sold":"68",
"vSectorName":"Meat"
},
"1":
{
"package_sold":"151",
"vSectorName":"Poultry"
},
"country":"United Kingdom"
}
]
How to show in graph dataProvider
AmCharts doesn't support nested JSON. You'll need to flatten your JSON into a single object so that your valueFields are distinct in each element of your array.
For example, this:
{
"0":
{
"package_sold":"68",
"vSectorName":"Meat"
},
"1":
{
"package_sold":"151",
"vSectorName":"Poultry"
},
"country":"United Kingdom"
}
can be turned into this:
{
"Meat_package_sold": 68,
"Poultry_package_sold": 151,
"country": "United Kingdom"
}
From there you can set your graph valueField to "Meat_package_sold" and "Poultry_package_sold". I'm assuming your categoryField is "country".
You'll either need to change your backend or write some some JS to remap your data to a format that AmCharts can recognize.
Edit: Here's a basic example that remaps your JSON data using JS:
var rawData = [{
"0": {
"package_sold": "88",
"vSectorName": "Meat"
},
"country": "France"
},
{
"0": {
"package_sold": "68",
"vSectorName": "Meat"
},
"1": {
"package_sold": "151",
"vSectorName": "Poultry"
},
"country": "United Kingdom"
}
]
var newData = [];
rawData.forEach(function(dataItem) {
var newDataItem = {};
Object.keys(dataItem).forEach(function(key) {
if (typeof dataItem[key] === "object") {
newDataItem[dataItem[key]["vSectorName"] + "_package_sold"] = dataItem[key]["package_sold"];
} else {
newDataItem[key] = dataItem[key];
}
});
newData.push(newDataItem);
});
console.log(JSON.stringify(newData));
Demo of your chart using the correct JSON format:
var chart = AmCharts.makeChart("chartdiv", {
"type": "serial",
"theme": "light",
"categoryField": "country",
"graphs": [{
"fillAlphas": 0.8,
"lineAlpha": 0.2,
"type": "column",
"valueField": "Meat_package_sold"
},
{
"fillAlphas": 0.8,
"lineAlpha": 0.2,
"type": "column",
"valueField": "Poultry_package_sold"
}
],
"dataProvider": [{
"Meat_package_sold": 88,
"country": "France",
}, {
"Meat_package_sold": 68,
"Poultry_package_sold": 151,
"country": "United Kingdom"
}, {
"Meat_package_sold": 120,
"Poultry_package_sold": 110,
"country": "Germany"
}]
});
html,
body {
width: 100%;
height: 100%;
margin: 0px;
}
#chartdiv {
width: 100%;
height: 100%;
}
<script src="//www.amcharts.com/lib/3/amcharts.js"></script>
<script src="//www.amcharts.com/lib/3/serial.js"></script>
<script src="//www.amcharts.com/lib/3/themes/light.js"></script>
<div id="chartdiv"></div>
This is dynamic json data, but to show how to use and build I defined it so.
In actual, i use ajax to get json data and then building it dynamically.
Here I had Generate Graph,GLName against its opening for each month comparatively. hope it will helpful for all
var resp=[
{
"MONTH_": "01",
"MONTH_NAME": "JAN",
"YEAR_": "2018",
"GL_NAME": "CASH,FACTORY, SITE,OFFICE ",
"GL_ID": "79,81,522,89",
"OPENING": "606294,0,24851,170392",
"RECEIPT": "1641300,40000,210850,82300",
"PAYMENT": "2074921,103209,168893,40000",
"CLOSING": "172673,149483,66808,0"
},
{
"MONTH_": "02",
"MONTH_NAME": "FEB",
"YEAR_": "2018",
"GL_NAME": " SITE,CASH,OFFICE ,FACTORY",
"GL_ID": "81,79,522,89",
"OPENING": "66808,172673,0,149483",
"RECEIPT": "102650,40000,3479000,200000",
"PAYMENT": "239379,168339,40000,3388527",
"CLOSING": "-69921,0,181144,263146"
},
{
"MONTH_": "03",
"MONTH_NAME": "MAR",
"YEAR_": "2018",
"GL_NAME": "FACTORY,CASH,OFFICE , SITE",
"GL_ID": "89,81,79,522",
"OPENING": "181144,-69921,0,263146",
"RECEIPT": "30000,40000,1943500,200000",
"PAYMENT": "69242,1806551,18177",
"CLOSING": "141902,400095,40000,111902"
}
]
var newChartDataArr = [];
var colNameArr = [];
var GLID = [];
var amtArr = [];
var newBarGraph = [];
myJsonString1 = JSON.stringify(resp);
var obj = JSON.parse(myJsonString1);
var obj1 = resp[0];
//spliting of GLName
if (obj1.GL_NAME.toString().indexOf(',') != -1) {
colNameArr = obj1.GL_NAME.split(',');
GLID =obj1.GL_ID.split(',');
} else {
colNameArr.push(obj1.GL_NAME);
GLID =obj1.GL_ID.split(',');
}
//Getting Month and Opening of GL
$.each(resp, function (i, value) {
var newObj = {};
newObj['MONTH_NAME'] = value.MONTH_NAME+"-"+value.YEAR_;
$.each(value, function (k, v) {
if (k == 'OPENING') {
for (var i = 0; i < colNameArr.length; i++) {
if (v.toString().indexOf(',') != -1) {
newObj[colNameArr[i]] = parseFloat(v.split(',')[i]);
} else {
newObj[colNameArr[i]] = parseFloat(v);
}
}
}
});
newChartDataArr.push(newObj); //GL with Opening
});
for (var i = 0; i < colNameArr.length; i++) {
let graph = {};
graph["id"] = "v-"+GLID[i];
graph["balloonText"] = colNameArr[i] + " [[category]] Amount:[[value]]",
graph["title"] = colNameArr[i];
graph["valueField"] = colNameArr[i];
graph["fillAlphas"] = 0.8;
graph["lineAlpha"] = 0.2;
graph["type"] = "column";
newBarGraph.push(graph);
}
chart = AmCharts.makeChart("Monthdiv", {
"type": "serial",
"theme": "light",
"categoryField": "MONTH_NAME",
"startDuration": 1,
"trendLines": [],
"legend": {
"position": "bottom",
"maxColumns": 2,
"useGraphSettings": true
},
"depth3D": 10,
"angle": 60,
"graphs": newBarGraph,
"guides": [],
"valueAxes": [
{
"position": "left",
"title": "Opening"
}
],
"categoryAxis": {
"gridPosition": "start",
"labelRotation": 90,
"title": "Months"
},
"allLabels": [],
"balloon": {},
"titles": [{
"text":"Monthly Sale"
}],
"dataProvider": newChartDataArr,
"export": {
"enabled": true
},
"listeners": [{
"event": "clickGraphItem",
"method": function (event) {
var gl_ID=(event.item.graph.id).slice(2);
var month = (event.item.category).slice(0, 3);
var calender = ['JAN', 'FEB', 'MAR', 'APR', 'MAY', 'JUN', 'JUL', 'AUG', 'SEP', 'OCT', 'NOV', 'DEC'];
var monthVal = calender.indexOf(month) + 1;
var year = (event.item.category).slice(4, 8);
$("#fromDate").val("01/" + monthVal + "/" + year);
$("#toDate").val("30/" + monthVal + "/" + year);
Daliy(gl_ID,event.item.category);
showSummary();
}
}]
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!-- Resources -->
<script src="https://www.amcharts.com/lib/3/amcharts.js"></script>
<script src="https://www.amcharts.com/lib/3/serial.js"></script>
<script src="https://www.amcharts.com/lib/3/themes/light.js"></script>
<div class="col-sm-12" id="Monthdiv" style="height: 370px;">

Missing date on Amcharts x-axis

I'm trying to build a simple graph. X-axis is month, Y-axis is value. Here is the demo of my graph
var chart = AmCharts.makeChart("chartdiv", {
"type": "xy",
"theme": "light",
"dataDateFormat": "DD-MM-YYYY",
"graphs": [
{
"id":"g8",
"balloon":{
"drop":true,
"adjustBorderColor":false,
"color":"#ffffff"
},
"bullet":"round",
"bulletBorderAlpha":1,
"bulletColor":"#FFFFFF",
"bulletSize":5,
"dashLength":0,
"hideBulletsCount":50,
"lineThickness":2,
"lineColor":"#67b7dc",
"title":"Store 8",
"useLineColorForBulletBorder":true,
"xField":"d1",
"yField":"p1",
"xAxis":"g8",
"balloonText":"<span style='font-size:18px;'>$[[d2]]</span><br>07/1/2017-12/31/2017"
}
],
"valueAxes": [
{
"id": "g8",
"axisAlpha": 1,
"gridAlpha": 1,
"axisColor": "#b0de09",
"color": "#b0de09",
"dashLength": 5,
"centerLabelOnFullp": true,
"position": "bottom",
"type": "date",
"minp": "DD-MM-YYYY",
"markPeriodChange": false,
}
],
"dataProvider": [
{
"d1":"01/01/2017",
"p1":"5353.9000"
},{
"d1":"02/01/2017",
"p1":"5353.9000"
},{
"d1":"01/02/2017",
"p1":"5288.9500"
},{
"d1":"01/03/2017",
"p1":"6850.9900"
},{
"d1":"01/04/2017",
"p1":"5543.1900"
},{
"d1":"01/05/2017",
"p1":"5519.0100"
},{
"d1":"01/06/2017",
"p1":"6191.7500"
}
]
});
https://jsfiddle.net/noroots/xru967ha/
I don't know why, but X-axis labels missing June and all labels looks like having left offset. How can I move it to the left and show missing month?
You could add data items before and after without drawing points:
"dataProvider": [{
"d1":"01/12/2016"
}, {
"d1":"01/01/2017",
"p1":"5353.9000"
}, ...
Please check the example here: https://jsfiddle.net/xru967ha/5/
Old Answer
Please check the example below. It's using AmSerialChart and then the datePadding plugin to set 15 extra days at the beginning and the end of your data.
"categoryAxis": {
"parseDates": true,
"minPeriod": "MM",
"prependPeriods": 0.5, // add 15 days start
"appendPeriods": 0.5 // add 15 days to end
}
var chart = AmCharts.makeChart("chartdiv", {
"type": "serial",
"theme": "light",
"marginRight": 40,
"marginLeft": 60,
"dataDateFormat": "DD-MM-YYYY",
"valueAxes": [{
"id": "v1",
"axisAlpha": 0,
"position": "left",
"ignoreAxisWidth": true,
"dashLength": 5
}],
"graphs": [{
"id": "g1",
"balloon":{
"drop":true,
"adjustBorderColor":false,
"color":"#ffffff"
},
"bullet": "round",
"bulletBorderAlpha": 1,
"bulletColor": "#FFFFFF",
"bulletSize": 5,
"hideBulletsCount": 50,
"lineThickness": 2,
"lineColor":"#67b7dc",
"title": "red line",
"useLineColorForBulletBorder": true,
"valueField": "p1",
"balloonText": "<span style='font-size:18px;'>[[value]]</span>"
}],
"chartCursor": {
"pan": true,
"valueLineEnabled": true,
"valueLineBalloonEnabled": true,
"cursorAlpha":1,
"cursorColor":"#258cbb",
"limitToGraph":"g1",
"valueLineAlpha":0.2,
"valueZoomable":true
},
"categoryField": "d1",
"categoryAxis": {
"parseDates": true,
"minorGridEnabled": true,
"axisColor": "#b0de09",
"color": "#b0de09",
"dashLength": 5,
"boldPeriodBeginning": false,
"markPeriodChange": false,
"minPeriod": "MM",
"prependPeriods": 0.5,
"appendPeriods": 0.5
},
"export": {
"enabled": true
},
"dataProvider": [
{
"d1":"01/01/2017",
"p1":"5353.9000"
},{
"d1":"02/01/2017",
"p1":"5353.9000"
},{
"d1":"01/02/2017",
"p1":"5288.9500"
},{
"d1":"01/03/2017",
"p1":"6850.9900"
},{
"d1":"01/04/2017",
"p1":"5543.1900"
},{
"d1":"01/05/2017",
"p1":"5519.0100"
},{
"d1":"01/06/2017",
"p1":"6191.7500"
}
]
});
#chartdiv {
width : 800px;
height : 500px;
}
<script src="https://www.amcharts.com/lib/3/amcharts.js"></script>
<script src="https://www.amcharts.com/lib/3/serial.js"></script>
<script src="//www.amcharts.com/lib/3/plugins/tools/datePadding/datePadding.min.js"></script>
<script src="https://www.amcharts.com/lib/3/plugins/export/export.min.js"></script>
<link rel="stylesheet" href="https://www.amcharts.com/lib/3/plugins/export/export.css" type="text/css" media="all" />
<script src="https://www.amcharts.com/lib/3/themes/light.js"></script>
<div id="chartdiv"></div>

Dynamic Data push for date based fields

I'm trying to push data dynamically to the dataProvider of XY charts in amcharts but I'm not able to achieve that.
My chart is not being drawn.
My x axis would be month and the y axis would be a numeric value.
I tried something like this
all the month and total arrays are declared . My obj looks something like this:
dataProviderObj{(date : 2015-Jan , y :80 , value :80 ),(date : 2015-Feb , y :70 , value :70)};
dataProviderObj={};
I'm trying to push like this
for(i=0;i<=month.length;i++){
dataProviderObj.push{(
"date" : month[i],
"y" : total[i],
"value" : total[i]
)}
}
dataprovider.push(dataProviderObj);
var chart = AmCharts.makeChart("chartdiv", {
"type": "xy",
"theme": "light",
"marginRight": 80,
"dataDateFormat": "YYYY-MMM",
"startDuration": 1.5,
"trendLines": [],
"balloon": {
"adjustBorderColor": false,
"shadowAlpha": 0,
"fixedPosition":true
},
"graphs": [{
"balloonText": "<div style='margin:5px;'><b>[[x]]</b><br>y:<b>[[y]]</b><br>value:<b>[[value]]</b></div>",
"bullet": "diamond",
"id": "AmGraph-1",
"lineAlpha": 0,
"lineColor": "#b0de09",
"fillAlphas": 0,
"valueField": "value",
"xField": "date",
"yField": "y"
}, {
"balloonText": "<div style='margin:5px;'><b>[[x]]</b><br>y:<b>[[y]]</b><br>value:<b>[[value]]</b></div>",
"bullet": "round",
"id": "AmGraph-2",
"lineAlpha": 0,
"lineColor": "#fcd202",
"fillAlphas": 0,
"valueField": "bValue",
"xField": "date",
"yField": "by"
}],
"valueAxes": [{
"id": "ValueAxis-1",
"axisAlpha": 0
}, {
"id": "ValueAxis-2",
"axisAlpha": 0,
"position": "bottom",
"type": "date",
"minimumDate": new Date(2015, 0, 01),
"maximumDate": new Date(2015, 12, 13)
}],
"allLabels": [],
"titles": [],
"dataProvider": dataprovider,
"export": {
"enabled": true
},
"chartScrollbar": {
"offset": 15,
"scrollbarHeight": 5
},
"chartCursor":{
"pan":true,
"cursorAlpha":0,
"valueLineAlpha":0
}
});
I want to get dynamic Date in x axis and dynamic numeric value in y axis with a value . Kindly help me draw such a xy Chart in amcharts
There are two issues -
1) Your logic for populating the dataprovider isn't right. You need to push directly to the dataprovider array in the loop. The logic should be:
var dataprovider = [];
for(i=0;i<=month.length;i++){
dataProvider.push({
"date" : month[i],
"y" : total[i],
"value" : total[i]
});
}
Note the placement of the parentheses and curly braces - you're calling the dataprovider array's push function with the parentheses and you're pushing an object ({ ... }) containing your data into the array.
2) "MMM" is not a supported in dataDateFormat. As you can see in AmCharts' formatting dates documentation, any format with an asterisk is not supported. Your data/dates should look like this in the resulting dataprovider array:
dataprovider = [{
"date": "2015-01",
"y": 19,
"value": 19
},
{
"date": "2015-02",
"y": 18,
"value": 18
},
// etc
]
Here's a demo with correctly formatted data
//dummy data:
var month = [ "2015-01", "2015-02", "2015-03", "2015-04", "2015-05", "2015-06", "2015-07", "2015-08", "2015-09", "2015-10", "2015-11", "2015-12"];
var total = [ 17, 16, 15, 16, 19, 20, 17, 20, 16, 19, 16, 18 ];
var dataprovider = [];
for(var i=0;i<=month.length;i++){
dataprovider.push({
"date" : month[i],
"y" : total[i],
"value" : total[i]
});
}
var chart = AmCharts.makeChart("chartdiv", {
"type": "xy",
"theme": "light",
"marginRight": 80,
"dataDateFormat": "YYYY-MM",
"startDuration": 1.5,
"trendLines": [],
"balloon": {
"adjustBorderColor": false,
"shadowAlpha": 0,
"fixedPosition": true
},
"graphs": [{
"balloonText": "<div style='margin:5px;'><b>[[x]]</b><br>y:<b>[[y]]</b><br>value:<b>[[value]]</b></div>",
"bullet": "diamond",
"id": "AmGraph-1",
"lineAlpha": 0,
"lineColor": "#b0de09",
"fillAlphas": 0,
"valueField": "value",
"xField": "date",
"yField": "y"
}, {
"balloonText": "<div style='margin:5px;'><b>[[x]]</b><br>y:<b>[[y]]</b><br>value:<b>[[value]]</b></div>",
"bullet": "round",
"id": "AmGraph-2",
"lineAlpha": 0,
"lineColor": "#fcd202",
"fillAlphas": 0,
"valueField": "bValue",
"xField": "date",
"yField": "by"
}],
"valueAxes": [{
"id": "ValueAxis-1",
"axisAlpha": 0
}, {
"id": "ValueAxis-2",
"axisAlpha": 0,
"position": "bottom",
"type": "date",
"minimumDate": new Date(2014, 11, 1),
"maximumDate": new Date(2016, 0, 1)
}],
"allLabels": [],
"titles": [],
"dataProvider": dataprovider,
"export": {
"enabled": true
},
"chartScrollbar": {
"offset": 15,
"scrollbarHeight": 5
},
"chartCursor": {
"pan": true,
"cursorAlpha": 0,
"valueLineAlpha": 0
}
});
<script type="text/javascript" src="//www.amcharts.com/lib/3/amcharts.js"></script>
<script type="text/javascript" src="//www.amcharts.com/lib/3/xy.js"></script>
<div id="chartdiv" style="width 100%; height: 400px"></div>

How to export amChart with transparent background?

How to export amChart with transparent background?
Here, is my code:
var chartData = [{
"country": "USA",
"visits": 4025,
"color": "#FF0F00"
}, {
"country": "China",
"visits": 1882,
"color": "#FF6600"
}, {
"country": "Japan",
"visits": 1809,
"color": "#FF9E01"
}, {
"country": "Germany",
"visits": 1322,
"color": "#FCD202"
}, {
"country": "UK",
"visits": 1122,
"color": "#F8FF01"
}, {
"country": "France",
"visits": 1114,
"color": "#B0DE09"
}, {
"country": "India",
"visits": 984,
"color": "#04D215"
}, {
"country": "Spain",
"visits": 711,
"color": "#0D8ECF"
}, {
"country": "Netherlands",
"visits": 665,
"color": "#0D52D1"
}, {
"country": "Russia",
"visits": 580,
"color": "#2A0CD0"
}, {
"country": "South Korea",
"visits": 443,
"color": "#8A0CCF"
}, {
"country": "Canada",
"visits": 441,
"color": "#CD0D74"
}, {
"country": "Brazil",
"visits": 395,
"color": "#754DEB"
}, {
"country": "Italy",
"visits": 386,
"color": "#DDDDDD"
}, {
"country": "Australia",
"visits": 384,
"color": "#999999"
}, {
"country": "Taiwan",
"visits": 338,
"color": "#333333"
}, {
"country": "Poland",
"visits": 328,
"color": "#000000"
}];
var chart = AmCharts.makeChart("chartdiv", {
type: "serial",
theme: "light",
dataProvider: [{
"year": 2005,
"income": 23.5,
"expenses": 18.1
}, {
"year": 2006,
"income": 26.2,
"expenses": 22.8
}, {
"year": 2007,
"income": 30.1,
"expenses": 23.9
}, {
"year": 2008,
"income": 29.5,
"expenses": 25.1
}, {
"year": 2009,
"income": 24.6,
"expenses": 25
}],
categoryField: "year",
startDuration: 1,
rotate: true,
categoryAxis: {
gridPosition: "start"
},
valueAxes: [{
position: "top",
title: "Million USD",
minorGridEnabled: true
}],
graphs: [{
type: "column",
title: "Income",
valueField: "income",
fillAlphas: 1,
balloonText: "<span style='font-size:13px;'>[[title]] in [[category]]:<b>[[value]]</b></span>"
}, {
type: "line",
title: "Expenses",
valueField: "expenses",
lineThickness: 2,
bullet: "round",
balloonText: "<span style='font-size:13px;'>[[title]] in [[category]]:<b>[[value]]</b></span>"
}],
legend: {
useGraphSettings: true
}
});
var image = new Image();
var btn = document.getElementById('export');
btn.onclick = function () {
var tmp = new AmCharts.AmExport(chart);
tmp.init();
tmp.output({
output: 'datastring',
format: 'jpg', "backgroundColor": "gray",
"backgroundAlpha": 0.3,
}, function (blob) {
image.src = blob;
console.log(image.src);
document.body.appendChild(image);
// var doc = new jsPDF('landscape');
// doc.addImage(image, 'JPEG', 10, 10 );
// doc.save('testingPDF.pdf');
printGraph1();
});
function printGraph1() {
var source = "../../Content/images/print-background.png";
var html = "<html style=' margin:0;height:100%;overflow:hidden;'><head><script>function step1(){\n" +
"setTimeout('step2()', 10);}\n" +
"function step2(){window.print();window.close()}\n" +
"</scri" + "pt><link rel='stylesheet' href='http://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css'><style type='text/css' media='print'></style></head><body style=' margin:0;height:100%;overflow:hidden;' onload='step1()' style='background-image: url(' " + source + "')'>\n" +
"<img src='" + source + "' style=' min-height:100%; min-width:100%;height:auto;width:auto;position:absolute; margin:auto;z-index:-1; '/>";
//$(".chartdata").height(700);
//$(".chartdata").width(300);
// $("#chart").css({'position': 'absolute', 'margin': 'auto', 'top': '0', 'right': '0','bottom': '0' ,'left': '0'});
// var divContent = $(".chartdata").html();
//var image1 = new Image();
//image1.src = image.src;
console.log(image.src);
var divCon = "<div style='width:100% position: absolute; margin: auto; top: 30%; right: 0;bottom: 0; left: 0; '>";
var divConEnd = "</div>";
//var imgDiv = "<div id='imge'></div>";
//$("#imge").appendChild(image);
//var img = "<img src='" + image.src + "/>";
Pagelink = "about:blank";
var pwa = window.open(Pagelink, "_new");
pwa.document.open();
pwa.document.write(html);
//pwa.document.write(divCon);
pwa.document.write("<div style=' position: absolute; margin: auto; top: 30%; '>");
pwa.document.write("<img style=' background-color:blue; 'src='" + image.src + "'/>");
//pwa.document.body.appendChild(image);
pwa.document.write("</div>");
// pwa.document.write(divConEnd);
pwa.document.write("<button type='submit' class='btn btn-primary'>Submit</button>");
pwa.document.write('</body ></html>');
pwa.document.close();
}
enter image description here
Use "transaprent" as backgroundColor:
tmp.output( {
"output": "datastring",
"format": "png",
"backgroundColor": "transparent",
"backgroundAlpha": 0.3
}, ...
Please note that you will need to use an image format that supports transparency, like PNG. JPEG does not support it.
In amCharts 4, you can define the backgroundColor which will use for exporting the chart as follows:
chart.exporting.backgroundColor = am4core.color("#f00", 0);
chart.exporting.getImage("png") // return a promise
In this way, amCharts will not use the background color from the parent.

Resources