Angular JSON from API to an Array of value - arrays

I have an API which gives me a JSON in the following format:
[{"timestamp":"1389442547000","PourcentRest":"50"},
{"timestamp":"1389442548000","PourcentRest":"55"},
{"timestamp":"1389868449000","PourcentRest":"45"}]
I need to turn the returned object into an array of values ​​for integration with highchart like this:
[[1389442547000,50],[1389442548000,55],
[1389868449000,45],[1389868450000,73],
[1391177296000,37],[1391177297000,45]]
I've been trying for several days, but I can't do it.
Here is the dataservice which interrogates the API
export class TankDetailsService {
PHP_API_SERVER = "http://MY-API";
constructor(private httpClient: HttpClient) {}
readMeasures(idCit: string): Observable<Measure[]>{
return this.httpClient.get<Measure[]>(`${this.PHP_API_SERVER}/restFillingApi/?idcit=${idCit}`);
}
Here is the part of my component.ts
export class TankDetailsComponent implements OnInit {
Measure: Measure[];
idCit: string;
chartOptions: object;
constructor(private route: ActivatedRoute, private TankDetailsService: TankDetailsService, private http: HttpClient) {
this.route.queryParams
.subscribe(params => {
this.idCit = params['idCit'];
console.log(this.idCit);
}
);
this.TankDetailsService.readMeasures(this.idCit).subscribe((Measure: Measure[])=>{
this.Measure = Measure;
console.log(this.arr);
this.chartOptions = {
chart: {
type: "spline"
},
title: {
text: "Volumes"
},
yAxis: {
title:{
text:"Volumes"
}
},
tooltip: {
pointFormat: '<span style="color:{series.color}">{series.name}</span>: <b>{point.y} %</b><br/>',
valueDecimals: 0,
split: true
},
series: [
{
name: 'Tokyo',
data: this.Measure
},
{
name: 'New York',
data: [[1389442547000,50],[1389442548000,55],[1389868449000,45],[1389868450000,73],[1391177296000,37],[1391177297000,45],[1391528879000,38],[1391528880000,71],[1392217092000,54],[1392217093000,69],[1392641513000,61],[1392641514000,72],[1393844672000,40],[1393844673000,63]]
},
{
name: 'Berlin',
data: [-0.9, 0.6, 3.5, 8.4, 13.5, 17.0, 18.6, 17.9, 14.3, 9.0, 3.9, 1.0]
},
{
name: 'London',
data: [3.9, 4.2, 5.7, 8.5, 11.9, 15.2, 17.0, 16.6, 14.2, 10.3, 6.6, 4.8]
}
]
};
console.log(this.chartOptions);
})
}
Please can you help me see it more clearly?

Please use below code after your API response then you will get the output as you want
let a = [{"timestamp":"1389442547000","PourcentRest":"50"},
{"timestamp":"1389442548000","PourcentRest":"55"},
{"timestamp":"1389868449000","PourcentRest":"45"}];
const outputArr = [];
for (let i = 0; i < a.length; i++) {
let b = [];
b.push(parseInt(a[i].timestamp), parseInt(a[i].PourcentRest));
outputArr.push(b);
}
console.log(outputArr);

Parsing your data to int and setting xAxis.type to 'datetime' solves it.
let data = [{"timestamp":"1389442547000","PourcentRest":"50"},
{"timestamp":"1389442548000","PourcentRest":"55"},
{"timestamp":"1389868449000","PourcentRest":"45"}]
function parseData() {
return data.map(data => [parseInt(data.timestamp), parseInt(data.PourcentRest)])
}
Highcharts.chart('container', {
xAxis: {
type: 'datetime'
},
series: [{
data: parseData()
}],
});
<script src="https://code.highcharts.com/highcharts.js"></script>
<div id="container"></div>

Related

How to add this GraphQL data to my pie chart in highcharts?

I would appreciate any help that I can get with this
I need to plot a pie chart with 4 standard pies: ABC, BCD, CDE and DEF
Each Pie has a data point coming in from my GraphiQL resolver which looks like this:
{
"data": {
"metrics": {
"A": 56147.85,
"B": 116480.51,
"C": 56147.85,
"D": 120329.45000000001,
}
}
}
This is my highchart code for piechart
function PieChart() {
const { loading, error, data } = useQuery(CONC, {
variables: {
Currency: 'USD',
Date: {
date: '2019-05-01',
date_range: ['2019-05-01', '2019-06-10'],
},
Options: {
a: {
prop: '44',
csprop: ['14', '14', '40', '60'],
},
d: {
prop: '104',
csprop: ['511', '289', '519', '62'],
},
},
C: 'G',
Incl: false,
DFilters: [
{
by: 'P',
values: [],
},
],
},
});
const Top = [];
const First = [];
const Second = [];
const Rest = [];
data &&
data.metrics.forEach((e) => {
Top.push(e['A']);
First.push(e['B']);
Second.push(e['C']);
Rest.push(e['D']);
});
return (
<HighchartWrapper
chartOptions={{
chart: {
type: 'pie',
height: 230,
// width: 565,
},
title: {
text: '',
},
tooltip: {
pointFormat: '{series.name}: <b>{point.percentage:.1f}%</b>',
},
accessibility: {
point: {
valueSuffix: '%',
},
},
exporting: {
enabled: false,
},
plotOptions: {
pie: {
allowPointSelect: true,
cursor: 'pointer',
dataLabels: {
enabled: true,
format: '<b>{point.name}</b>: {point.percentage:.1f} %',
},
},
},
series: [
{
name: 'R',
data: [
{ name: 'ABC', y: Top},
{ name: 'BCD', y: First},
{ name: 'CDE', y: Second},
{ name: 'DEF', y: Rest},
],
},
],
}}
/>
);
}
export default memo(PieChart);
PROBLEM:
The GraphiQL query is generating results.
But I believe it's the way I am trying to push data that's giving me an empty pie chart
Thank you all in advance

Spring MVC: How to display Hashmap keys and values in highcharts

I want to display data from my database into highcharts (bars).
I tried using HashMap to pass values from controller to javascript.
MyController.java:
#GetMapping("/Hist")
public String barGraph(Model model) {
ApplicationContext context =
new ClassPathXmlApplicationContext("Spring-Module.xml");
PTS_POINTS_HISTORY_DAO ptsHistDAO = (PTS_POINTS_HISTORY_DAO) context.getBean("PtsPointsHistoryDAO");
model.addAttribute("surveyMap", ptsHistDAO.barGraph());
//ptsHistDAO.barGraph() returns Map<String, Integer>
return "Hist";
}
hist.jsp:
<div id="containerx" style="width:100%; height:400px;"></div>
<script>
Highcharts.chart('containerx', {
chart: {
type: 'column'
},
title: {
text: 'Total Redeem'
},
xAxis: {
categories: ['${surveyMap.keySet()}']
},
yAxis: {
max: 10000,
min:0,
title: {
text: 'Numbre of Loylaty Points Redeemed'
}
},
tooltip: {
pointFormat: '<span style="color:{series.color}">{series.name}</span>: <b>{point.y}</b> ({point.percentage:.0f}%)<br/>',
shared: true
},
plotOptions: {
column: {
stacking: 'permillion'
}},
series: [{
name: 'Fulfilled',
data: [9667, 0, 5694, 2752, 200]
}, {
name: 'Cancelled',
data: [500, 3000, 300, 2, 1]
}, {
name: 'Pending',
data: [3, 500, 400, 2, 50]
}]
});
</script>
I expected that each key will be represented by their value in bar graph, but actually all the keys represents only the first value in graph.
expected :
x1:20151514 y1: 9667 cancelled, 500 fullfilled, 3 pending
what i get:
x1: [20151514,20151513,20151512..] y1: 9667 cancelled, 500 fullfilled, 3 pending
Highcharts requires categories property to be an array of strings. Your result was a string, which required to use JSON.parse method:
var str = "[0013-05-08, 2010-11-17, 0015-05-09, 0024-01-01, 0021-01-01]"
var res = str.replace(/,\s/g, '","');
var res2 = res.replace('[', '["');
var res3 = res2.replace(']', '"]')
Highcharts.chart('container', {
xAxis: {
categories: JSON.parse(res3)
},
series: [{
data: [1, 2, 3, 4, 5]
}]
});
Live demo: http://jsfiddle.net/BlackLabel/k4L3whu5/
API Reference: https://api.highcharts.com/highcharts/xAxis.categories

ionic 2 highchart not visible

I added highchart looking Page source but not visible on page
I followed this https://www.youtube.com/watch?v=FSg8n5_uaWs
how can ı solve this problem
my codes;
ts;
export class VerilerPage {
chartOptions : any;
constructor(public navCtrl: NavController, public navParams: NavParams) {
this.chartOptions={
chart: {
type: 'bar'
},
title: {
text: 'Fruit Consumption'
},
xAxis: {
categories: ['Apples', 'Bananas', 'Oranges']
},
yAxis: {
title: {
text: 'Fruit eaten'
}
},
series: [{
name: 'Jane',
data: [1, 0, 4]
}, {
name: 'John',
data: [5, 7, 3]
}]
}
}
html;
<chart options="chartOptions" type="chart" ></chart>
Since you are using angular 2/4, you have to enclose options with []
<chart [options]="chartOptions" type="chart" ></chart>

Reactjs With Handsontable cell validation function is not invoking

I have declared cell validation function but in cells property but it is not getting invoked and no error is also thrown
I have declared the function definition as member function and trying to call it from componentDidMount function
Also some suggestions regarding using handsontable with react would be great!
Below is my code
import React from 'react';
import Handsontable from 'handsontable/dist/handsontable';
let hot = {};
let columns = [];
let data = '';
class SpreadSheet extends React.Component {
constructor(props){
super(props);
this.state = {
data : [
{year: "2016", name: 'John', age: 23, contact: 8000142880},
{year: "2015", name: 'Doe', age: 22, contact: 9494858568},
{year: "2013", name: 'Jack', age: 21, contact: 7878989825},
{year: "2012", name: 'Joe', age: 20, contact: 9898454526},
]
}
columns = [
{ data: 'year', type: 'text' },
{ data: 'name', type: 'text' },
{ data: 'age', type: 'numeric' },
{ data: 'contact', type: 'numeric' }
]
}
getData = () => {
var datafromtable = document.getElementById('foo');
//console.log(datafromtable);
data = hot.getData();
console.log(data);
}
negativeValueRenderer = () => (instance, td, row, col, prop, value, cellProperties) => {
console.log('arguments');
//Handsontable.renderers.TextRenderer.apply(this, arguments);
//return;
}
componentDidMount() {
var container = document.getElementById('foo');
hot = new Handsontable(container, {
data: this.state.data,
minSpareCols: 1 ,
minSpareRows: 1,
minCols: 5,
minRows: 5,
rowHeaders: true,
colHeaders: ['Year','Name','Age','Contact'],
columns: columns,
cells: function (row, col, prop) {
console.log(this);
this.renderer = this.negativeValueRenderer;//not getting triggered
},
contextMenu: true
});
}
render() {
return (
<div>
<div id="foo"></div>
<button onClick = {this.getData}>Get Data</button>
{data}
</div>
);
}
}
export default SpreadSheet;
Are you trying to apply the negativeValueRenderer to each cell, or just the Age column?
Give this a shot:
constructor(props) {
super(props);
this.negativeValueRenderer = this.negativeValueRenderer.bind(this);
}
...
negativeValueRenderer(instance, td, row, col, prop, value, cellProperties) {
renderers.NumericRenderer.apply(this, arguments);
if (parseInt(value, 10) < 0) {
td.style.color = 'red';
}
}
...
hot = new Handsontable(container, {
data: this.state.data,
minSpareCols: 1 ,
minSpareRows: 1,
minCols: 5,
minRows: 5,
rowHeaders: true,
colHeaders: ['Year','Name','Age','Contact'],
columns: columns,
columns={[
{
data: 'year',
},
{
data: 'name',
},
{
data: 'age',
validator: this.negativeValueValidator,
},
{
data: 'contact',
},
contextMenu: true
});

Export Google Chart to Excel Sheet in Angular

Im using ng-google-chart to create charts from data I receive from a database. I store the data in a table. I need to export both the table and the chart.
I'm using the following technique to export tables (where "exportable" is the div the contains the table):
$scope.export = function ()
{
var blob = new Blob([document.getElementById('exportable').innerHTML], {
type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8"
});
saveAs(blob, "Record.xls");
alert("export done");
};
I cannot find any way to add the chart to this file.
This is the code to generate a chart
var chart1 = {};
chart1.type = "ColumnChart";
chart1.cssStyle = "height:400px; width:500px;";
chart1.data = {
"cols": [
{ id: "gender", label: "Gender", type: "string" },
{ id: "number", label: "number", type: "number" }
], "rows": [
{
c: [
{ v: "male" },
{ v: $scope.male, f: $scope.male }
]
},
{
c: [
{ v: "female" },
{ v: $scope.female }
]
}
]
};
chart1.options = {
"title": "",
"isStacked": "true",
"fill": 20,
"displayExactValues": true,
"vAxis": {
"title": "Number", "gridlines": { "count": 6 }
},
"hAxis": {
"title": "gender"
}
};
chart1.formatters = {};
$scope.chart = chart1;
}
To getImageURI of the chart, wait for the ready event and call the function.
Then you can add the image somewhere on the page.
You can even hide the original chart if needed...
Following is an example of loading the image URI into another element.
google.load('visualization', '1', {packages:['corechart'], callback: drawChart});
function drawChart() {
var data = google.visualization.arrayToDataTable([
["Element", "Density", { role: "style" } ],
["Copper", 8.94, "#b87333"],
["Silver", 10.49, "silver"],
["Gold", 19.30, "gold"],
["Platinum", 21.45, "color: #e5e4e2"]
]);
var view = new google.visualization.DataView(data);
view.setColumns([0, 1,
{ calc: "stringify",
sourceColumn: 1,
type: "string",
role: "annotation" },
2]);
var options = {
title: "Density of Precious Metals, in g/cm^3",
width: 600,
height: 400,
bar: {groupWidth: "95%"},
legend: { position: "none" },
};
var chart = new google.visualization.ColumnChart(document.getElementById("chart_div"));
google.visualization.events.addListener(chart, 'ready', function () {
document.getElementById("chart_image").insertAdjacentHTML('beforeEnd', '<img alt="Chart Image" src="' + chart.getImageURI() + '">');
});
chart.draw(view, options);
}
<script src="https://www.google.com/jsapi"></script>
<span>CHART</span>
<div id="chart_div"></div>
<br/>
<span>IMAGE</span>
<div id="chart_image"></div>

Resources