How to get all json values in line chart - javascript

I have many Json values, using them I am going to create a line chart but it shows only one value in the chart. I am a newbie to javascript and have an idea to plot all values in chart. please anybody give jsfiddle example for this issue.
HTML code
<div id="chartContainer" class="chart">
Script
$.getJSON('dashboard_summary.php?', function(data) {
var len = data.length
$.each(data, function(i, v) {
chart(v.Date,v.Tip,v.Revenue,len);
});
});
function chart (dates,Tip,Rev,len) {
var chart = new CanvasJS.Chart("chartContainer", {
title: {
text: "Revenue",
fontSize: 15
},
axisX: {
gridColor: "Silver",
tickColor: "silver",
valueFormatString: "DD/MMM"
},
toolTip: {
shared:true
},
theme: "theme2",
axisY: {
gridColor: "Silver",
tickColor: "silver"
},
legend: {
verticalAlign: "center",
horizontalAlign: "right"
},
data: [
{
type: "line",
showInLegend: true,
lineThickness: 2,
name: "Tip",
markerType: "square",
color: "#F08080",
dataPoints: [
{
x: new Date(dates),
y: parseInt(Tip)
}
]
},
{
type: "line",
showInLegend: true,
name: "Revenue",
color: "#20B2AA",
lineThickness: 2,
dataPoints: [
{
x: new Date(dates),
y: parseInt(Rev)
}
]
}
],
legend: {
cursor: "pointer",
itemclick: function(e) {
if (typeof(e.dataSeries.visible) === "undefined" || e.dataSeries.visible) {
e.dataSeries.visible = false;
} else {
e.dataSeries.visible = true;
}
chart.render();
}
}
});
chart.render();
};
Json data
{
"Date": "2014-01-30",
"CarsParked": "1",
"RevenueWithTip": "0",
"Revenue": "0",
"Tip": "0",
},
{
"Date": "2014-01-31",
"CarsParked": "10",
"RevenueWithTip": "10",
"Revenue": "7",
"Tip": "3",
},
{
"Date": "2014-02-28",
"CarsParked": "28",
"RevenueWithTip": "55",
"Revenue": "47",
"Tip": "8",
}

Based on your code, I can see why the chart shows only one point, which is the last data point of those points expected to be shown on the chart. Here is the problem:
var len = data.length;
/* Loop through each item in the data */
$.each(data, function(i, v) {
chart(v.Date,v.Tip,v.Revenue,len); /* Draw a chart with one point */
});
So you end up drawing many charts with the last chart which has the last data point to replace all the previous charts.
Instead, you should adjust the foreach block as follow and draw the chart once you've converted the data into an array of points.
$.getJSON('dashboard_summary.php?', function(data) {
var Tips = [];
var Revs = [];
$.each(data, function(i, v) {
Tips.push({ x: new Date(v.Date), y: parseInt(v.Tip) });
Revs.push({ x: new Date(v.Date), y: parseInt(v.Revenue) });
});
chart(Tips, Revs);
});
Also, you can format the x-axis to make the chart look prettier (The format of the x-axis here is designed for the data given above. In your application, you may have to use another format style depending on the actual data):
function chart (Tips, Revs) {
var chart = new CanvasJS.Chart("chartContainer", {
title: {
text: "Revenue",
fontSize: 15
},
axisX: {
gridColor: "Silver",
tickColor: "silver",
valueFormatString: "DD/MMM",
interval:14,
intervalType: "day"
},
toolTip: {
shared:true
},
theme: "theme2",
axisY: {
gridColor: "Silver",
tickColor: "silver"
},
legend: {
verticalAlign: "center",
horizontalAlign: "right"
},
data: [
{
type: "line",
showInLegend: true,
lineThickness: 2,
name: "Tip",
markerType: "square",
color: "#F08080",
dataPoints: Tips
},
{
type: "line",
showInLegend: true,
name: "Revenue",
color: "#20B2AA",
lineThickness: 2,
dataPoints: Revs
}
],
legend: {
cursor: "pointer",
itemclick: function(e) {
if (typeof(e.dataSeries.visible) === "undefined" || e.dataSeries.visible) {
e.dataSeries.visible = false;
} else {
e.dataSeries.visible = true;
}
chart.render();
}
}
});
chart.render();
}
A jsFiddle is made here for your review.

Updated codes. it Works >> Pastebin
<!DOCTYPE HTML>
<html>
<head>
<script type="text/javascript" src = "http://canvasjs.com/wp-content/themes/bootstrap_child/assets/js/jquery-1.8.3.min.js"> </script>
<script type="text/javascript" src="http://canvasjs.com/assets/script/canvasjs.min.js"></script>
</head>
<body>
<div id="chartContainer" class="chart">
<script type="text/javascript">
data=[
{
"Date": "2014-01-30",
"CarsParked": "1",
"RevenueWithTip": "0",
"Revenue": "0",
"Tip": "0",
},
{
"Date": "2014-01-31",
"CarsParked": "10",
"RevenueWithTip": "10",
"Revenue": "7",
"Tip": "3",
},
{
"Date": "2014-02-28",
"CarsParked": "28",
"RevenueWithTip": "55",
"Revenue": "47",
"Tip": "8",
}];
var len = data.length;
$.each(data, function(i, v) {
chart(v.Date,v.Tip,v.Revenue,len);
});
function chart (dates,Tip,Rev,len) {
var chart = new CanvasJS.Chart("chartContainer", {
title: {
text: "Revenue",
fontSize: 15
},
axisX: {
gridColor: "Silver",
tickColor: "silver",
valueFormatString: "DD/MMM"
},
toolTip: {
shared:true
},
theme: "theme2",
axisY: {
gridColor: "Silver",
tickColor: "silver"
},
legend: {
verticalAlign: "center",
horizontalAlign: "right"
},
data: [
{
type: "line",
showInLegend: true,
lineThickness: 2,
name: "Tip",
markerType: "square",
color: "#F08080",
dataPoints: [
{
x: new Date(dates),
y: parseInt(Tip)
}
]
},
{
type: "line",
showInLegend: true,
name: "Revenue",
color: "#20B2AA",
lineThickness: 2,
dataPoints: [
{
x: new Date(dates),
y: parseInt(Rev)
}
]
}
],
legend: {
cursor: "pointer",
itemclick: function(e) {
if (typeof(e.dataSeries.visible) === "undefined" || e.dataSeries.visible) {
e.dataSeries.visible = false;
} else {
e.dataSeries.visible = true;
}
chart.render();
}
}
});
chart.render();
}
</script>
</body>
</html>

jsFiddle
Update Code:
dataRevenue=
[
{ x: new Date(2014, 00,30), y: 0 },
{ x: new Date(2014, 01,31), y: 7},
{ x: new Date(2014, 02,28), y: 47}
];
dataTip =[
{ x: new Date(2014, 00,30), y: 0 },
{ x: new Date(2014, 01,31), y: 3},
{ x: new Date(2014, 02,28), y: 8}
];
var chart = new CanvasJS.Chart("chartContainer",
{
theme: "theme2",
title:{
text: "line chart"
},
axisX: {
valueFormatString: "MMM",
interval:1,
intervalType: "month"
},
axisY:{
includeZero: false
},
data: [
{
type: "line",
//lineThickness: 3,
dataPoints: dataTip
},
{
type: "line",
//lineThickness: 3,
dataPoints: dataRevenue
}
]
});
chart.render();

Related

Chart JS - Group Array Results on y axis

I think I am close to solving this but I am missing something critical. I have an array of "new" items that I am trying to plot on a chart to indicate how old they are. I can get the chart to load and plot the data but like items are not grouping onto the same line. Is there a way I can force the chart to put like types onto the same axis line in the chart? i.e. the 2 SAFE AE results load onto the same line? Any guidance would be appreciated!
var whatsNewArray = [{
"type": "EAC",
"age": -16
},
{
"type": "EAC",
"age": -58
},
{
"type": "DSCC",
"age": -36
},
{
"type": "SAFE AE",
"age": -95
},
{
"type": "SAFE AE",
"age": -94
}
]
new Chart(document.getElementById("myWHATSNEWChart"), {
type: 'scatter',
data: {
datasets: [{
data: whatsNewArray.map(function(a) {
return a.age;
}),
backgroundColor: ["#acc6ff"],
label: "New Items",
pointRadius: 10,
fill: true
}]
},
options: {
indexAxis: 'y',
maintainAspectRatio: false,
responsive: true,
layout: {
padding: 20
},
scales: {
y: {
ticks: {
color: "#a3a3a3"
},
type: "category",
labels: whatsNewArray.map(function(a) {
return a.type;
}),
grid: {
color: "#a3a3a3",
borderColor: "#a3a3a3"
}
},
x: {
title: {
display: true,
text: "MINUTES AGO",
color: "#a3a3a3"
},
ticks: {
color: "#a3a3a3"
},
beginAtZero: true,
grid: {
color: "#a3a3a3",
borderColor: "#a3a3a3"
},
border: {
color: "#a3a3a3"
}
}
},
plugins: {
legend: {
display: false,
title: {
color: "#a3a3a3"
},
labels: {
color: "#a3a3a3"
}
},
title: {
display: false,
//text: 'What is New',
color: "#a3a3a3"
}
}
}
});
<link href="https://cdnjs.cloudflare.com/ajax/libs/mdb-ui-kit/6.1.0/mdb.dark.min.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/mdb-ui-kit/6.1.0/mdb.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/4.2.0/chart.umd.js"></script>
<div class="chart-container mb-4" style="position: relative;width:100%;height:250px;background-color:#283044;">
<canvas id="myWHATSNEWChart"></canvas>
</div>
I've created this minimal example, for your problem. You can add your custom options as you wish.
You have to treat the y-axis as an index, so .findIndex(el => el.type == elem.type) is checking if the elem.type exists in an array and returns the index of the found element.
var whatsNewArray = [{
"type": "EAC",
"age": -16
},
{
"type": "EAC",
"age": -58
},
{
"type": "DSCC",
"age": -36
},
{
"type": "SAFE AE",
"age": -95
},
{
"type": "SAFE AE",
"age": -94
},
{
"type": "DSCC",
"age": -2
},
{
"type": "EL",
"age": -2
},
{
"type": "PSY",
"age": -20
},
{
"type": "CNGRO",
"age": -80
},
{
"type": "CNGRO",
"age": -69
},
];
let label = [...new Map(whatsNewArray.map(item =>
[item["type"], item["type"]])).values()];
let data = whatsNewArray.map(function(elem, index) {
return {
x: elem.age,
y: label.indexOf(elem.type)
}
});
const _data = {
datasets: [{
label: 'Scatter Dataset',
data: data,
backgroundColor: 'rgb(255, 99, 132)'
}],
};
const config = {
type: 'scatter',
data: _data,
options: {
responsive: true,
layout: {
padding: 20
},
pointRadius: 10,
fill: true,
scales: {
y: {
autofill: false,
labels: label,
ticks: {
callback: function(value, index, ticks) {
return value % 1 == 0 ? label[value] : ''
}
},
}
}
}
};
new Chart(document.getElementById("myWHATSNEWChart"), config);
<link href="https://cdnjs.cloudflare.com/ajax/libs/mdb-ui-kit/6.1.0/mdb.dark.min.css" rel="stylesheet" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/mdb-ui-kit/6.1.0/mdb.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/4.2.0/chart.umd.js"></script>
<canvas id="myWHATSNEWChart"></canvas>
Explanation: So the index of an array label is being recognized as y-axis data [0,1,2....].
This returns distinct values:
[...new Map(whatsNewArray.map(item => [item["type"], item["type"]])).values()];
This checks if the value is an integer, for removing decimal values in this context.
value % 1 == 0

Overlapping stack chart in Canvas JS

i have a code which should give me an overlapping bar chart , one inside other in canvas js , something like below
Output Needed
So it should be combination of stacked horizontal graph , and one overlapping graph inside the first ( as in pic)
but am getting everything inside one main graph
below is the code .
var chart = new CanvasJS.Chart("chartContainer", {
theme: "light2",
title: {
text: "Chart Title"
},
reversed:true,
data: [
{
type: "error",
whiskerThickness: 0,
color: "#004ca0",
dataPoints: [
{ label: "Alpha", y: [0 , 71] },
]
},
{
type: "column",
axisXType: "secondary",
color: "#34dc00",
dataPoints: [
{ label: "Alpha", y: 60 },
]
},
{
type: "column",
axisXType: "secondary",
color: "#3cfa00",
dataPoints: [
{ label: "Alpha", y: 50 },
]
},
]
});
chart.render();
chart.data[0].set("stemThickness", chart.get("dataPointWidth") * 4 + 10);
<div id="chartContainer" style="height: 360px; width: 100%;"></div>
Thanks
var chart = new CanvasJS.Chart("chartContainer", {
theme: "light2",
title: {
text: "Chart Title"
},
reversed:true,
data: [
{type: "error", axisXType: "secondary", color: "#34dc00", dataPoints: [{ label: "Alpha", y: [ 0, 100 ] }, ]},
{type: "column", axisXType: "secondary", color: "#004ca0", dataPoints: [{ label: "Alpha", y: 71 }, ] },
{type: "column", axisXType: "secondary", color: "#ff0000", dataPoints: [{ label: "Alpha", y: 50 }, ] }
]
});
chart.render();
chart.data[0].set("stemThickness", chart.get("dataPointWidth") * 4 + 10);
<script src="https://canvasjs.com/assets/script/canvasjs.min.js"></script>
<div id="chartContainer" style="height: 360px; width: 100%;"></div>
In the code that you have shared, you are using column chart whereas in the screenshot shared it needs Stacked Bar Chart. Using Stacked Bar / Stacked Bar 100% & Error chart, you can achieve as shown in the screenshot shared. Below is the working code.
var chart = new CanvasJS.Chart("chartContainer", {
dataPointWidth: 70,
axisX: {
lineThickness: 0,
tickLength: 0,
labelFormatter: function(e) {
return "";
}
},
axisY: {
includeZero: true,
lineThickness: 0,
gridThickness: 0,
tickLength: 0,
labelFormatter: function(e) {
return "";
}
},
toolTip: {
shared: true
},
data: [{
type: "stackedBar100",
name: "Unique Opens: 33.3%",
showInLegend: true,
color: "#23a9e8",
dataPoints: [
{ x: 1, y: 33.3 }
]
}, {
type: "error",
name: "Unique Clicks: 33.3%",
showInLegend: true,
legendMarkerType: "square",
linkedDataSeriesIndex: 0,
stemThickness: 25,
whiskerThickness: 0,
color: "#336a84",
dataPoints: [
{ x: 1, y: [0, 33.3] }
]
}, {
type: "stackedBar100",
name: "Unique Opens: 66.7%",
showInLegend: true,
color: "#dfe3e4",
dataPoints: [
{ x: 1, y: 66.7 }
]
}]
});
chart.render();
<script src="https://canvasjs.com/assets/script/canvasjs.min.js"></script>
<div id="chartContainer" style="height: 100px; width: 100%;"></div>

How to make dynamic charts in Javascript with a JSON File

So, I am new to Javascript, but I have a code to make a stable bar chart, but I need to make it dynamic.
MY JSON File format is:
"valid_columns_counts": {
"Sr no.": 0,
"Domain": 37,
"Company Name": 0,
"Address": 36,
"Industry": 38,
"Phone Number": 30,
"Zipcode": 33,
"email": 14}
I ran this code:
window.onload = function () {
var dataPoints = [];
var chart = new CanvasJS.Chart("chartContainer", {
animationEnabled: true,
title:{
},
axisY: {
title: "Percentage",
titleFontColor: "#4F81BC",
},
toolTip: {
shared: true
},
legend: {
cursor:"pointer",
itemclick: toggleDataSeries
},
data:
{
type: "column",
name: "Consistency",
legendText: "Consistency",
axisYType: "secondary",
showInLegend: true,
dataPoints: dataPoints
}
});
function addData(data) {
for (var i = 0; i < data.length; i++) {
dataPoints.push({
x: data[i].valid_columns_counts
y: data[i].valid_columns_counts
});
}
}
chart.render();
$.getJSON("localhost/sample_output.json", addData);
}
But this code shows blank page when runned.Please if someone can help me.

how to map serial and data points using json Array

I am creating multi serial line chart using highchart.
My Json (cleanData) look like this...
[{
"key": "port_A",
"value": [
[1447596900000, 0],
[1447596960000, 0],
[1447597020000, 1]
]
}, {
"key": "port_B",
"value": [
[1447596900000, 0],
[1447596960000, 4]
]
} {
"key": "port_C",
"value": [
[1447596900000, 0],
[1447596960000, 0],
[1447597020000, 1]
}]
How can I map "key" as serial and "value" as data points on highchart
$(document).ready(function () {
Highcharts.setOptions({
colors: ['#058DC7', '#50B432', '#ED561B', '#DDDF00', '#24CBE5', '#64E572', '#FF9655', '#FFF263', '#6AF9C4']
});
var chart = new Highcharts.Chart({
chart: {
renderTo: 'container',
type: 'pie',
zoomType: 'y',
resetZoomButton: {
position: {
// align: 'right', // by default
// verticalAlign: 'top', // by default
x: 0,
y: -30
}
},
options3d: {
enabled: true,
alpha: 15,
beta: 15,
depth: 50
}
},
title: {
text: 'Users by region',
x: -20 //center
},
subtitle: {
text: '',
x: -20
},
xAxis: {
type: 'category',
//categories: ['APAC', 'test2', 'test3', 'test4'],
labels: {
rotation: -45,
style: {
'fontSize': '10px',
'fontFamily': 'Verdana, sans-serif',
'color': '#333',
'text-transform': 'uppercase',
'font-weight': '600'
}
}
},
yAxis: {
min: 0,
title: {
text: 'Number of users '
}
},
legend: {
enabled: false
},
tooltip: {
pointFormat: '#users: <b>{point.y:.1f}</b>'
},
credits: {
enabled: false
},
exporting: {
enabled: false
},
plotOptions: {
column: {
depth: 25
}
},
series: []
});
var cleanData1 = JSON.stringify(myArray);
var cleanData = $.parseJSON(cleanData1);
console.log(JSON.stringify(cleanData));
chart.series = cleanData;
});
You need to iterate over your json and put the name and data in an object as like below
var seriesData = [];
$.each(clearData, function(i,item){
seriesData.push({name:clearData[i].key,data:clearData[i].value});
console.log("seriesData"+JSON.stringify(seriesData));
});
See working fiddle here

Issues with amcharts

I am making stock charts with amcharts library . Here is what I have achieved
And here is what I want
You can compare both picture and see I have cylindrical and moving avg graph (dashed lines) but I am not able to add spikes which are showing at the bottom of graph in original one. (Pink and orange color). I don't know how to add those spikes in stock graph .
My data is dynamic so I can't create a js fiddle but I can provide my function here-
function load_stock_graph(graph_type, history, title, aggregate){
// DEFINE CHART PLUGINS
AmCharts.averageGraphs = 0;
AmCharts.addMovingAverage = function (dataSet, panel, field, aggregate, col ,graph) {
// update dataset
var avgField = "avg"+AmCharts.averageGraphs;
dataSet.fieldMappings.push({
fromField: avgField,
toField: avgField});
// calculate moving average
var fc = 0;
var sum = 0;
for (var i = 0; i < dataSet.dataProvider.length; i++) {
// console.log(aggregate[i].ema_0008)
var dp = dataSet.dataProvider[i];
if (dp[field] !== undefined) {
sum += dp[field];
fc++;
if (aggregate[i] !== undefined){
if(col == '08'){
dp[avgField] = aggregate[i].ema_0008;
}else if(col == '15'){
dp[avgField] = aggregate[i].ema_0015;
}else if(col == '20'){
dp[avgField] = aggregate[i].ema_0020;
}
}
}
}
// create a graph
graph.valueField = avgField;
panel.stockGraphs.push(graph);
// increment average graph count
AmCharts.averageGraphs++;
}
// CHART DATA
var chartData = [];
var chartData1 = [];
generateChartData(history);
function generateChartData(history) {
var firstDate = new Date();
firstDate.setHours(0, 0, 0, 0);
firstDate.setDate(firstDate.getDate() - 2000);
for (var i = 0; i < history.length; i++) {
var date = new Date(history[i].date);
var val = Math.round(Math.random() * (30) + 100);
chartData[i] = ({
date: date,
open: history[i].open,
close: history[i].close,
high: history[i].high,
low: history[i].low,
volume: history[i].volume,
value: val
});
}
}
// CHART CONFIG
var chartConfig = {
type: "stock",
pathToImages : "/static/img/amcharts/",
dataSets: [{
fieldMappings: [{
fromField: "open",
toField: "open"
}, {
fromField: "close",
toField: "close"
}, {
fromField: "high",
toField: "high"
}, {
fromField: "low",
toField: "low"
}, {
fromField: "volume",
toField: "volume"
}, {
fromField: "value",
toField: "val"
}],
color: "#fff",
dataProvider: chartData,
title: title,
categoryField: "date",
compared: false,
},
{
fieldMappings: [{
fromField: "value",
toField: "value"
}],
color: "#fff",
dataProvider: chartData,
title: title,
categoryField: "date"
},
],
panels: [{
title: "Value",
percentHeight: 70,
stockGraphs: [{type: graph_type,
id: "g1",
openField: "open",
closeField: "close",
highField: "high",
lowField: "low",
valueField: "close",
lineColor: "#fff",
fillColors: "#fff",
negativeLineColor: "#db4c3c",
negativeFillColors: "#db4c3c",
fillAlphas: 1,
comparedGraphLineThickness: 2,
columnWidth: 0.7,
useDataSetColors: false,
comparable: true,
compareField: "close",
showBalloon: false,
//proCandlesticks: true
} ],
stockLegend: {
valueTextRegular: undefined,
periodValueTextComparing: "[[percents.value.close]]%"
}
},
{
title: "Volume",
percentHeight: 40,
marginTop: 1,
columnWidth: 0.6,
showCategoryAxis: false,
valueAxes: [{
usePrefixes: true
}],
stockGraphs: [ {
valueField: "volume",
openField: "open",
type: "column",
showBalloon: false,
fillAlphas: 1,
lineColor: "#fff",
fillColors: "#fff",
negativeLineColor: "#db4c3c",
negativeFillColors: "#db4c3c",
useDataSetColors: false,
} ],
stockLegend: {
markerType: "none",
markerSize: 0,
labelText: "",
periodValueTextRegular: "[[value.close]]"
}
}
],
panelsSettings: {
color: "#fff",
plotAreaFillColors: "#333",
plotAreaFillAlphas: 1,
marginLeft: 60,
marginTop: 5,
marginBottom: 5
},
chartScrollbarSettings: {
graph: "g1",
graphType: "line",
usePeriod: "WW",
backgroundColor: "#333",
graphFillColor: "#666",
graphFillAlpha: 0.5,
gridColor: "#555",
gridAlpha: 1,
selectedBackgroundColor: "#444",
selectedGraphFillAlpha: 1
},
categoryAxesSettings: {
equalSpacing: true,
gridColor: "#555",
gridAlpha: 1
},
valueAxesSettings: {
gridColor: "#555",
gridAlpha: 1,
inside: false,
showLastLabel: true
},
chartCursorSettings: {
pan: true,
valueLineEnabled:true,
valueLineBalloonEnabled:true
},
legendSettings: {
color: "#fff"
},
stockEventsSettings: {
showAt: "high"
},
balloon: {
textAlign: "left",
offsetY: 10
},
periodSelector: {
position: "bottom",
periods: [ {
period: "DD",
count: 10,
label: "10D"
}, {
period: "MM",
count: 1,
label: "1M"
}, {
period: "MM",
count: 6,
selected: true,
label: "6M"
}, {
period: "YYYY",
count: 1,
label: "1Y"
}, {
period: "YYYY",
count: 2,
label: "2Y"
}, {
period: "YTD",
label: "YTD"
}, {
period: "MAX",
label: "MAX"
} ]
},
"export": {
"enabled": true,
"backgroundColor": "#fff",
"dataDateFormat": "YYYY-MM-DD"
}
}
// ADD INDICATORS
// ema_0008
AmCharts.addMovingAverage(chartConfig.dataSets[0], chartConfig.panels[0], 'value',aggregate, '08', {
useDataSetColors: false,
color: "#ccffcc",
lineColor: "#F4F009",
title: "aggregate ema 0008",
dashLength: 3
});
// ema_0015
AmCharts.addMovingAverage(chartConfig.dataSets[0], chartConfig.panels[0], 'value',aggregate, '15',{
useDataSetColors: false,
color: "#ccffcc",
lineColor: "#2C7F1D",
title: "aggregate ema 0015",
dashLength: 3
});
// ema_0020
AmCharts.addMovingAverage(chartConfig.dataSets[0], chartConfig.panels[0], 'value',aggregate, '20',{
useDataSetColors: false,
color: "#ccffcc",
lineColor: "#A109E8",
title: "aggregate ema 0020",
dashLength: 3
});
// Empty chart instance so that chart loaded via ajax can work correctly
AmCharts.charts = [];
// CREATE CHART
var chart = AmCharts.makeChart("chartdiv", chartConfig);
}
Sounds like you just need to add another line graph in a separate panel.
Here's how to do it:
1) Add additional field in your data. You currently have open, high, low, close field. Let's add another one, say, "pink".
2) Update Data Set's fieldMappings property, to accommodate for the change:
[{
fromField: "open",
toField: "open"
}, {
fromField: "close",
toField: "close"
}, {
fromField: "high",
toField: "high"
}, {
fromField: "low",
toField: "low"
}, {
fromField: "volume",
toField: "volume"
}, {
fromField: "value",
toField: "val"
}, {
fromField: "pink",
toField: "pink"
}]
3) Add additional stock panel and a graph that will use the newly added data field:
{
percentHeight: 20,
showCategoryAxis: false,
stockGraphs: [{
valueField: "pink",
showBalloon: false,
lineColor: "#fb02fe",
lineThickness: 2,
useDataSetColors: false
}]
}
If you would have wanted to add the indicator to some existing panel, you would just need to define the graph in it's stockGraphs array. I.e.:
{
percentHeight: 20,
showCategoryAxis: false,
stockGraphs: [{
valueField: "pink",
showBalloon: false,
lineColor: "#fb02fe",
lineThickness: 2,
useDataSetColors: false
}, {
valueField: "red",
showBalloon: false,
lineColor: "#cc0000",
lineThickness: 2,
useDataSetColors: false
}]
}
Use this process to add as many indicators as you need.
Here's a working demo (with random values)
http://codepen.io/amcharts/pen/938b09efeabca4596c0a2cdaea60a269

Categories

Resources