Dygraphs not accepting variable as Label for array dataset - javascript

I'm tying out dygraphs an it´s pretty fun.
For some reason though it does not accept a variable as labels for the array containing the data. I have formatted the string to exactly look like the "hardcoded" entry but it just won´t work.
Here are some snippets to let you know what i mean.
var select =('<?php echo implode('","', $select); ?>');
var label='"X"'+ ',"'+select+'"';
g = new Dygraph(
// containing div
document.getElementById("graphdiv"),allData,
{
labels: [label], // I tried it with and without the brackets, no difference
legend:'always',
title:'Abweichung der Messerte',
titleHeight:32,
ylabel:'<?php echo $art?>',
xlabel:'Zeit',
showRangeSelector: true,
digitsAfterDecimal: 5,
strokeWidth: 1.5,
drawPoints: true,
}
);
If i log label to the console it looks like this, depending on the selected numbers:
""X","10002","10003""
Still i get the folling error
"Mismatch between number of labels ("X","10002","10003") and number of columns in array (3)"
My array format for allData is [time,Value1,Value2] and works fine if i hardcode the labels.
Please tell me what i´m doing wrong :-)
greetings David

You need to pass an array of strings, not a comma-separated string of labels.
i.e.
['X', 'Y1', 'Y2']
and not
'X,Y1,Y2'

Related

PHP Array to JS array and restructure

I have two PHP strings that looks like this (obviously shortened for the question):
$year [
[0]=>2003
[1]=>2003
[2]=>2004
[3]=>2004
[4]=>2005
[5]=>2005
]
$cost [
[0]=>200
[1]=>300
[2]=>400
[3]=>500
[4]=>410
[5]=>510
]
I need to turn the PHP arrays above into a JAVASCRIPT array formatted exactly as below:
var newData=[
['2003', 200,300],
['2004', 400,500],
['2005', 410,510]
];
When I type in the JS array implicitly (as above) all works fine (ie the graphics render correctly). However after several hours of trying different approaches, I cannot work out how to easily generate the newData array dynamically (ie from PHP arrays as shown) in exactly the JS Array format shown.
Your quest can be separated in two tasks:
First of all you want to combine both arrays. I guess you want to do this based on the keys they have. There are multiple functions for that in PHP, like array_combine or array_reduce.
Yet for your case the easiest way is a for_each loop, because you have duplicate values in the $year array.
$combined_array = [];
foreach ($year as $id => $year_val) {
if (!array_key_exists($year_val, $combined_array)) {
$combined_array[$year_val] = [(string)$year_val];
}
$combined_array[$year_val][] = $cost[$id];
}
Now you have the years as keys, what you do not want, so you can use array_values to remove the keys again.
$combined_array = array_values($combined_array);
The second task is quite easy: Go to the PHP file, that loads the script you want to provide the array to. Add this before you load the script:
<script>
var myPhpArray = <?php echo json_encode($combined_array) ?>;
</script>
After that the PHP array is accessible from JS in the variable `myPhpArray.
if you respect the structure in the example, the following would do the job:
<?php
$year = [
0 => 2003,
1 => 2003,
...
];
$cost = [
0 => 200,
1 => 300,
...
];
for($i=0;$i<SIZE_OF_ARRAY;$i+=2)
$newData[] = [(string) $year[$i], $cost[$i], $cost[$i+1]];
?>
Now in the javascript portion of the code you just need:
<script>
var newData = <?= json_encode($newData); ?>
</script>
Note that i didnt use the quotes between the php code because i do want the javascript to parse the php output as javascript code and not as a javascript string.
Thanks for all the help. Your answers showed I was going about things the right way (json_encode etc). What has happened though is that the legacy system producing the PHP Arrays was not correcting the values for integers rather than strings. The recipient plug in needed INTs -- see the output array format in the question
So json_encoding the php array worked OK - but it was encoding string rather than INT data values. Fixed that and now it all seems fine.
PS If you look at the orginal question yyou will see the OP array in JS needed two datatypes. And of course it was only getting strings. Lesson there for sure!
Heres the snippet
var a = ['1','2','3'];
var result = a.map(function (x) {
return parseInt(x, 10);

Pass an array from PHP to JS

hi i have a big problem i try 3 weaks to solve it but i didn't make anything i have or an errors or i don't take nothing from the results.
i pas an array from query ST_AsGeoJSON from a php code in the javascript code.
there are in the same file html this two codes i get the array from php to javascrypt with this line of code
var jsonAr= <?php echo json_encode($Arresu) ?>;
if i print the jsonAr i receve with document.write(jsonAr); it is give me this format
{ "type":"LineString","coordinates":[[25.9980559326738,39.2420282528175],......,,[26.0486275566016,39.2291388086281]]},{"type":"LineString","coordinates":[[26.0486275566016,39.2291388086281],......[]]}
if i try to take the coordinates and pot it in an array i try this jsonAr.coordinates[0][0] but i did not take any result , i don't know how i take the coordinates
jsonAr.coordinates[0] will give you the first coordinate. jsonAr.coordinates[0][0] only gives you the first number of the first coordinate.
It looks like you want to assign two values to your variable
jsonAr = {...},{...}
Maby you want to try somethig like this:
jsonAr = [{...},{...}]
jsonAr[0].coordinates[0][0] //25.9980559326738
Or
jsonAr = [{...},{...}]
draw_function(jsonAr[0].coordinates[0][0],jsonAr[1].coordinates[0][0]) //25.9980559326738,26.0486275566016

loading csv into nvd3 to make discrete bar chart

I have the following CSV file:
Fun,Stupid,Yes,No
50,-20,100,70
I'd like to load it into nvd3 to make a discrete bar chart. I know it's easy but it's taking me way to long to manipulate the data.
I've tried the following:
d3.csv("/path/to/file", function(data){
console.log(data);
});
and I get the following object which isn't working with nvd3:
[{Fun:50, Stupid: -20, Yes: 100, No: 70}]
Thanks.
nvd3 is expecting a fairly specific data form so you need to get your data into that form. The form that it is expecting is:
[
{
key: "totals",
values: []
}
];
Where the empty array is filled with the objects from d3.csv and note that nv is expecting the name of the array of your objects to be called values.
So the first step is to create an empty object like this:
var exampleData = [
{
key: "totals",
values: []
}
];
Then fill it with your data:
data.forEach(function (d){
d.value = +d.value
exampleData[0].values.push(d)
})
This all needs to be inside your d3.csv call.
To use this format you need to have your csv file organised into columns with your names in one column and your values in another like:
label, value
Fun, 50
Stupid, -20
And here's a link to a working example

HighStocks Array Series

Im creating a singleline series chart using dates and closing prices from yahoo. I have converted the dates into JS timestamps and put them in an array named timeStampArray and put the closing prices into an array named closePrices.
I can populate the chart with data like so:
data : [
[ 1361750400000, 442.80],
[ 1361491200000, 450.81]
],
I wish to use the data from my arrays and the API says to use an array with two values for x and y, like this
data: [[5, 2], [6, 3], [8, 2]]
therefore can I combine my two arrays so that they fit this format?
I can only find examples of how to combine my arrays into key-value pairs like this {'test1':'1', 'test2':'2'};
Also when I create the chart using hardcoded data it orders the dates in ascending order but I want it to keep the ordering that they are input, e.g 25th Feb before 22nd Feb as this is showing historical data.
Is there a way to correct this?
Heres the jsFiddle of my current code: http://jsfiddle.net/mXnZy/
update: ive tried
var timeClose = new Array();
for(var i=0; i<data.query.results.quote.length; i++)
{
timeClose.push( [timeStampArray[i], closePrices[i]] );
}
however this outputs [1361750400000, 442.80, 1361491200000, 450.81] which is wrong.
If you mean that you want them sorted in reverse order, you can use the 'reversed' property on the x axis:
http://api.highcharts.com/highstock#xAxis.reversed
If you mean that you want them listed in whatever order they're entered, without being sorted, it will be much more complicated.
You could provide ordinal x values, and provide the date as additional data. You could then use the axis label formatter to show the dates that you wish.

Highcharts breaks up my data array in a strange way

I'm using Highcharts (link to a specific demo -- click View Options to compare below code) to render some data for personal-use.
[Note: this is almost definitely a me-related error, so I don't mean to insinuate that Highcharts is at fault -- it's really a wonderful api!]
When setting the series.data field of the chart object, I encounter strange array sectioning.
For instance, this works fine:
series: [{
name: 'seriesName',
data: [22, 24, 15]
}]
And three data points are plotted with values 22, 24 and 15.
However,
series: [{
name: 'sillySeries',
data: chartData[0]
}]
renders 3 points with the values 2, 4 and 5 and the titles of the points are 2, 2 and 1 respectively... that is, it's splitting the array entries into a title and then a value for two-digit numbers.
console.log shows me that chartData looks like
22,24,15,2010-9,2010-10,2010-11
(3 values for 3 months)
Although the actual arrays are more like [22,24,15][2010-9,2010-10,2010-11]
My 2d-array chartData[][] has [column][row] indices for the data, and I figured that asking for chartData[0] would return an array.
Perhaps my question should be: How do I return a 1d array from a 2d array representation for setting properties/values in javascript objects? It seems like I'm probably overlooking something very obvious.
edit:
data: [24]
plots one point at 24, awesome.
data: '24'
splits up the data as title and then value, effectively plotting a point at 4 and not 24.
So the representation becomes a string when I try to pass an array to the data field. Any way I can do like string.toArray ?
edit 2:
chartData[col][row] is declared as an empty array
var chartData = [];
and subsequently filled up with values by iterating over an HTML table's rows and columns, where the innermost loop contents look like
chartData[cellIndex][rowIndex] = $(currentCell).text();
While chartData is probably an array, it sounds like chartData[0] is a string. When you use an array index on a string you get the character at that position, which is exactly what you are experiencing...
renders 3 points with the values 2, 4 and 5 and the titles of the points are 2, 2 and 1 respectively... that is, it's splitting the array entries into a title and then a value for two-digit numbers.
There are many ways to define arrays within arrays in javascript; here is one:
var chartData = [
[22,24,15]
,['2010-9','2010-10','2010-11']
];
parseInt() saved the day.
something like
for (i=0; i<chartData[0].length; ++i) {
columnOne.push(parseInt(chartData[0][i]);
}
gave me an array that I could then use to display the data with the data field in the object notation
data: columnOne
or more literally
chart1.series[0].data = columnOne;
Thank you James for pointing out
While chartData is probably an array, it sounds like chartData[0] is a string.
which lead to my discovery that the data in my array was actually all strings, which I kept this way because some fields are strings, some are dates (YYYY-MM-DD) and some are just ints.
Many thanks to you both =)
Well, this is not a real answer, but might help you.
Highcharts enables you to preprocess certain options. In your case, you could do something like :
options.series[0].data = new Array(1, 0, 4);
doc reference : http://www.highcharts.com/documentation/how-to-use#options
If this fails, comment above.

Categories

Resources