I want to dynamically create a CanvasJS chart depending on N amount of objects from a JSON array. If a JSON array has 3 objects, the web page should be able to display 3 charts.
<div class="container-fluid" id="spectraContainers">
</div>
Through the id "spectraContainers", I have a javascript function that dynamically creates a new div with a unique id. In that same function, a new chart is created with its unique id.
document.getElementById("chartContainers").innerHTML += '<div class="row"> <div id="chart_container_' + chartNumber + '" style="width: 100 %; height: 500px; ">Container </div></div>';
...
...
...
var chartContainerID = "chartcontainer_" + chartNumber;
var chart = new CanvasJS.Chart(chartContainerID, {
animationEnabled: true,
zoomEnabled: true,
theme: "light2",
title: {
text: chartTitle,
},
axisX: {
title: "x axis label",
gridDashType: "dash",
gridThickness: 2
},
axisY: {
title: "y axis label",
gridDashType: "dash",
gridThickness: 2
},
dataPointMaxWidth: 20,
dataPointWidth: 10,
data: [{
type: "column",
dataPoints: points
}]
});
chart.render();
I've verified that all values are valid. It seems like only ONE canvasJS chart (the third object from the json array) can be rendered in a page within this function. If I were to specifically generate a chart for index 0 or 1 in the json array, the specified index for the chart will be rendered.
I know it's possible to render multiple canvasJs charts by manually creating a new chart variable for each uniqueID. However, I would like to dynamically generate N-amount of charts. I am pretty new to javascript and would appreciate any advice!!
Using innerHTML replaces the contents of div element rather than appending child element. Try using append method.
Related
I found that I can create nice scatter plot with CanvasJS into my HTML templates (see the link: http://canvasjs.com/docs/charts/chart-types/html5-scatter-chart/)
I am creating a website using Django and a MySQL database.
In one of my tables (models) I have 3 fields VARCHAR containing different values:
- the 1st field contains values for X axis.
- The 2nd field contains values for Y axis.
- The 3rd field contains one letter labels.
Here is an example for one entry if it is not clear:
1st field:
999.99;-89.01;-60.29;-145.83;-140.76;-148.24;-88.70;56.92;69.08;-121.37
2nd field:
143.12;146.51;143.73;177.58;121.68;116.45;-14.05;20.77;15.82;168.20
3rd field:
CPPEEECTTE
As you can see, values are separated by ";" in fields 1 and 2.
there are 10 values in field 1, 10 values in field 2, and 10 corresponding letter labels.
All fields are 1 long string.
So my question is simple, I don't know how to make a for loop in javascript so that those coordinates will be taken in the scatter chart.
Here is the example of the canvasjs for scatter chart I want to obtain:
<!DOCTYPE HTML>
<html>
<head>
<script type="text/javascript">
window.onload = function () {
var chart = new CanvasJS.Chart("chartContainer",
{
title:{
text: "Title of my scatter chart"
},
data: [
{
type: "scatter",
dataPoints: [
{ x: 999.99, y: 143.12 },
{ x: -89.01, y: 146.51 },
{ x: -60.29, y: 143.73 },
{ x: -145.83, y: 177.58 },
{ x: -140.76, y: 121.68 },
{ x: -148.24, y: 116.45 }
]
}
]
});
chart.render();
}
</script>
<script type="text/javascript" src="/assets/script/canvasjs.min.js"></script>
</head>
<body>
<div id="chartContainer" style="height: 300px; width: 100%;">
</div>
</body>
</html>
All I want is to generate coordinates in dataPoints with a for loop.
The 3 fields will be 3 rows in a HTML table.
The 3rd field will be used to associate a color to a letter. (Example: C = blue, P = green, E = yellow, T = red).
I have absolutely no idea how to make that in javascript.
If someone is experienced in JS, I would really appreciate some help.
You can do so by traversing the arrays(of x,y values and color) and converting them to the format required by CanvasJS and then updating the chart options.
for(var i = 0; i < xVal.length; i++) {
chart.options.data[0].dataPoints.push({
x: parseFloat(xVal[i]),
y: parseFloat(yVal[i]),
color: colorArr[i]
});
}
Here's a jsfiddle for the same.
I recently updated highstock in which I used a chart that displayed values with an "extended range", i.e. where the min and max date is set outside the boundaries of the chart data.
After the update (which fixed some other bugs) I noticed that the last data point in the navigator series at the bottom is not correct according to the data in the actual series. As can be seen, there's an additional data point at the far right in the bottom that doesn't exist in the actual series.
This can be viewed at http://jsfiddle.net/ab96pnjf/ as well
The code that creates the chart is the following
$(function () {
var fromdate = new Date('2011-04-01');
var todate = new Date('2012-05-21');
var series = [{
color: 'red',
data: MSFT,
name: 'MSFT'
}];
$('#container').highcharts('StockChart', {
navigator: {
series: {
data: series[0].data,
color: '#4572A7',
fillOpacity: 0.05
}
},
xAxis: {
ordinal: false,
min: fromdate.getTime(),
max: todate.getTime()
},
legend: {
enabled: true
},
series: series
});
});
Now, if I change the navigator.series property to
navigator: {
series: series
}
the navigator chart is correct, as in the values are cut off at the right when there is no more data available. This is what I want; the only problem is that the color is the same as the series, and I want it to use my custom color, as in the first example.
So how do I configure HighStock to cut off the last value in the navigator chart while at the same time being able to use a custom color for the series?
Hm, well I have a "quick fix" to this problem, as I am not sure how I would configure highcharts to do it for me.
Using jQuery I can extract the line in the navigator, since highcharts (at least) applies a class to the series. It sets the class name for all series including the one in the "main area", but the last one is the navigator series it seems, or every odd series if there is more than one highcharts chart in the document.
$(function () {
// ... as previous
$('#container').highcharts('StockChart', {
navigator: {
series: series
},
// ... as previous
});
// added code to apply a custom style to the navigator line diagram
var navseries = $('.highcharts-series:last').children();
// can be undefined if the series has no data points
if (navseries) {
navseries.css('stroke', '#4572A7');
navseries.css('strokeWidth', 1);
navseries.css('fillOpacity', 0.05);
}
});
I'm using jquery chart to draw line chart and i need to add some string to dataField.I'm getting data from data base and include that in dataField.my graph is creating correctly and i only need to change dataField.
categoryAxis: {
text: 'Category Axis',
textRotationAngle: 90,
dataField: '{$this->graphField_Date}',
showTickMarks: true,
valuesOnTicks: false,
tickMarksInterval: 1,
tickMarksColor: '#888888',
unitInterval: 1,
gridLinesInterval: 1,
gridLinesColor: '#888888',
axisSize: 'auto'
},
{$this->graphField_Date} gets the week numbers of given period and i need to add "week" after the number how can do that.(eg 1 week,2 week)currently i'm getting only 1,2,3 etc.
categoryAxis.dataField = '{$this->graphField_Date}' + ' week'
Edit:
You could manipulate the DOM after the data has been loaded. In the success function of you ajax call ( if you are using ajax ), or just after the data has been added to the DOM add:
$('.dateFieldClass').append(' week');
This is assuming you have the date field data in an element with the class dateFieldClass
I'm creating a handful of pie charts using Google Charts. The majority of the graph options for the charts I'm creating are the same, except the titles. Is it possible to maintain a default set of options but write certain specific options for each graph (in this case, I just need to set a title).
Here's an example of the code I'm using:
var graphOptions = {
is3D: true,
pieSliceText: 'label',
colors: ['#F9B641', '#FBCB75', '#FCE1B0', '#FFF8EB', '#FFFFFF'],
backgroundColor: 'transparent',
titleTextStyle: {
color: '#FFF'
},
legend: {
textStyle: {
color: '#FFF'
}
},
chartArea: {
width: '90%',
height: '80%'
}
};
function pieChart1() {
// Create and populate the data table.
var data = google.visualization.arrayToDataTable([
['Gender', 'Number'],
['Male', 216],
['Female', 238]
]);
// Create and draw the visualization.
var chart = new google.visualization.PieChart(document.getElementById('pieChart1'));
chart.draw(data, graphOptions);
}
function pieChart2() {
// Create and populate the data table.
var data = google.visualization.arrayToDataTable([
['Gender', 'Number'],
['Male', 116],
['Female', 98]
]);
// Create and draw the visualization.
var chart = new google.visualization.PieChart(document.getElementById('pieChart2'));
chart.draw(data, graphOptions);
}
How would I go about setting the title option for each graph while still pulling the options from graphOptions?
As David explained, you can create an options object, and then edit properties of that object individually.
Here is a jsfiddle that shows it in action.
Note: you cannot see the titles because the BG and font color is white. Just do a ctrl+a to select everything and see them hidden there
Basically, you create a variable both functions can access (in your case graphOptions). In each function you set a new variable called options to equal graphOptions. You can then change the title property of the options variable to whatever you want without changing your default options template graphOptions, and use the options variable to draw the graph.
For your code, that means adding this code to each function:
var options = graphOptions;
options.title = "Pie Chart X"
You can change the title to whatever is appropriate, different for each graph. Then in the graph draw command, you change graphOptions to options to get
chart.draw(data, options);
Normally you'd do:
var options = { title: 'My Chat Title' };
In your case add title to your graphOptions object then do:
graphOptions.title = "The New Title";
for each graph.
Situation:
I have a function that dumps input data into an HTML block element, eg:
function national(){
x=Number($('#nationalBudget').val());
a=x*2;
$('#one').text(a);}
Then it prints the input into any element with the id="one"
<span id="one"></span>
This is fine, but I would like to incorporate a jQuery Bargraph. The bargraph that I am using is fed by an array:
coolnessGraph = new Array(
[100000,'ROI w/ Local Spending'],
[200000,'ROI w/o Local Spending']
$("#ROIchart").jqBarGraph({
data: coolnessGraph, // array of data for your graph
title: false, // title of your graph, accept HTML
barSpace: 10, // this is default space between bars in pixels
width: 400, // default width of your graph
height: 200, //default height of your graph
color: '#F8981D', // if you don't send colors for your data this will be default bars color
colors: false, // array of colors that will be used for your bars and legends
lbl: '', // if there is no label in your array
sort: false, // sort your data before displaying graph, you can sort as 'asc' or 'desc'
position: 'bottom', // position of your bars, can be 'bottom' or 'top'. 'top' doesn't work for multi type
prefix: '', // text that will be shown before every label
postfix: '', // text that will be shown after every label
animate: true, // if you don't need animated appearance change to false
speed: 2, // speed of animation in seconds
legendWidth: 100, // width of your legend box
legend: false, // if you want legend change to true
legends: false, // array for legend. for simple graph type legend will be extracted from labels if you don't set this
type: false, // for multi array data default graph type is stacked, you can change to 'multi' for multi bar type
showValues: true, // you can use this for multi and stacked type and it will show values of every bar part
showValuesColor: '#fff' // color of font for values
});
Problem:
I would like to replace the hard numbers (e.g. 100000 & 200000) in the array with the output that is dumped into my HTML object. I've tried the following:
var TestVariable = <span id="one"></span>;
coolnessGraph = new Array(
[TestVariable,'ROI w/ Local Spending'],
and just about every other iteration of syntax I could think up to make the process work. I also tried waiting to fire the graph after the first calculation has been run.
Is there an error my logic?...syntax?...any help would be greatly be appreciated.
If I'm reading correctly, you only need to pass $('#one').text(), or a variation of that, into the array. Am I missing something?