React + json output in chart - json

I have a simple json file:
{
"id": 1,
"name": "Bitcoin",
"quantity": 1,
"price": 1,
"old_price": 0.99,
"info": "The most famous one",
"archived_data": [
{
"id": 0,
"name": "jan",
"sold": 5,
"bought": 3
},
{
"id": 1,
"name": "feb",
"sold": 15,
"bought": 30
},
{
"id": 2,
"name": "mar",
"sold": 5,
"bought": 3
},
{
"id": 3,
"name": "apr",
"sold": 15,
"bought": 30
}
]
}
I now want to display them in my chart:
import CanvasJSReact from '../plugins/canvasjs.react';
import React, {Component} from 'react';
const CanvasJSChart = CanvasJSReact.CanvasJSChart;
class CryptoChart extends Component {
constructor(props) {
super(props);
this.toggleDataSeries = this.toggleDataSeries.bind(this);
}
toggleDataSeries(e){
e.dataSeries.visible = !(typeof (e.dataSeries.visible) === "undefined" || e.dataSeries.visible);
this.chart.render();
}
render() {
const options = {
theme: "light2",
animationEnabled: true,
axisX: {
title: "Months"
},
axisY: {
title: "Sold",
titleFontColor: "#007bff",
lineColor: "#007bff",
labelFontColor: "#007bff",
tickColor: "#007bff"
},
axisY2: {
title: "Bought",
titleFontColor: "#51CDA0",
lineColor: "#51CDA0",
labelFontColor: "#51CDA0",
tickColor: "#51CDA0"
},
toolTip: {
shared: true
},
legend: {
cursor: "pointer",
itemclick: this.toggleDataSeries
},
data: [
{
type: "spline",
name: "Sold",
showInLegend: true,
xValueFormatString: "MMM YYYY",
yValueFormatString: "#,##0 Units",
dataPoints: [
{ x: new Date(2020, 0, 1), y: this.props.crypto.archived_data[0].sold },
{ x: new Date(2020, 1, 1), y: this.props.crypto.archived_data[1].sold },
{ x: new Date(2020, 2, 1), y: this.props.crypto.archived_data[2].sold },
{ x: new Date(2020, 3, 1), y: this.props.crypto.archived_data[3].sold },
{ x: new Date(2020, 4, 1), y: this.props.crypto.archived_data[4].sold },
{ x: new Date(2020, 5, 1), y: this.props.crypto.archived_data[5].sold },
{ x: new Date(2020, 6, 1), y: this.props.crypto.archived_data[6].sold },
{ x: new Date(2020, 7, 1), y: this.props.crypto.archived_data[7].sold },
{ x: new Date(2020, 8, 1), y: this.props.crypto.archived_data[8].sold },
{ x: new Date(2020, 9, 1), y: this.props.crypto.archived_data[9].sold },
{ x: new Date(2020, 10, 1), y: this.props.crypto.archived_data[10].sold },
{ x: new Date(2020, 11, 1), y: this.props.crypto.quantity}
]
},
{
type: "spline",
name: "Bought",
axisYType: "secondary",
showInLegend: true,
xValueFormatString: "MMM YYYY",
yValueFormatString: "$#,##0.#",
dataPoints: [
{ x: new Date(2020, 0, 1), y: this.props.crypto.archived_data[0].bought },
{ x: new Date(2020, 1, 1), y: this.props.crypto.archived_data[1].bought },
{ x: new Date(2020, 2, 1), y: this.props.crypto.archived_data[2].bought },
{ x: new Date(2020, 3, 1), y: this.props.crypto.archived_data[3].bought },
{ x: new Date(2020, 4, 1), y: this.props.crypto.archived_data[4].bought },
{ x: new Date(2020, 5, 1), y: this.props.crypto.archived_data[5].bought },
{ x: new Date(2020, 6, 1), y: this.props.crypto.archived_data[6].bought },
{ x: new Date(2020, 7, 1), y: this.props.crypto.archived_data[7].bought },
{ x: new Date(2020, 8, 1), y: this.props.crypto.archived_data[8].bought },
{ x: new Date(2020, 9, 1), y: this.props.crypto.archived_data[9].bought },
{ x: new Date(2020, 10, 1), y: this.props.crypto.archived_data[10].bought },
{ x: new Date(2020, 11, 1), y: this.props.crypto.quantity }
]
}
]
}
return (
<div>
<CanvasJSChart options = {options} onRef={ref => this.chart = ref} />
</div>
);
}
} export default CryptoChart;
The this.props.crypto.quantity works as expected, but the this.props.crypto.archived_data[0].sold and this.props.crypto.archived_data[0].bought don't work: the app crashes and the console says
TypeError: Cannot read property '0' of undefined
Does anyone know how to output this?
Edit: Ive made a react.new here so its easier to see what is going wrong and maybe how it can be fixed

Related

Apex charts in Angular 9

I have some problem using apex charts in angular 9, essentially I'm able to see the chart (line chart) when I mock the data as in the first screenshot, but I can't get data from REST API, I mean the chart disappears.
mocked datas
This is the method containing the chart:
drawGraph(){
this.projectService.getLineChartData(this.getID()).then((data) =>{
for(let i = 0; i<data.resourceListSize; i++){
this.chartOptions = {
series: [
{
name: "data",
data: [28, 29, 33, 36, 32, 32, 33]
},
{
name: "Low - 2013",
data: [12, 11, 14, 18, 17, 13, 13]
}
],
chart: {
height: 350,
type: "line",
dropShadow: {
enabled: true,
color: "#000",
top: 18,
left: 7,
blur: 10,
opacity: 0.2
},
toolbar: {
show: false
}
},
colors: ["#77B6EA", "#545454"],
dataLabels: {
enabled: true
},
stroke: {
curve: "smooth"
},
title: {
text: "Average High & Low Temperature",
align: "left"
},
grid: {
borderColor: "#e7e7e7",
row: {
colors: ["#f3f3f3", "transparent"], // takes an array which will be repeated on columns
opacity: 0.5
}
},
markers: {
size: 1
},
xaxis: {
categories: ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul"],
title: {
text: "Month"
}
},
yaxis: {
title: {
text: "Temperature"
},
min: 5,
max: 40
},
legend: {
position: "top",
horizontalAlign: "right",
floating: true,
offsetY: -25,
offsetX: -5
}
};
}
})
}
Any help would be appreciated! Thank you
Step 1,
set the configuration with out data like below(minimum configuration)
this.chartOptions = {
series: [],
chart: {
height: 350,
type: "line"
},
xaxis: {}
}
Step 2:
Data from api response and set to "chartoptions" variable,
this.chartOptions.series=[{
name: "data",
data: [28, 29, 33, 36, 32, 32, 33]
}, {
name: "Low - 2013",
data: [12, 11, 14, 18, 17, 13, 13]
}
];
this.chartOptions.xaxis=
{
categories: ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul"]
}

highchart activity gauge chart using json data from a file

I am new to using highcharts.js. I want to create an activity gauge chart using data from a json file or url. I have understood how they draw the chart but failed to understand the data format used in json to display the chart.
Here is my code
var options = {
chart: {
type: 'solidgauge',
marginTop: 50
},
title: {
text: 'Activity',
style: {
fontSize: '24px'
}
},
tooltip: {
borderWidth: 0,
backgroundColor: 'none',
shadow: false,
style: {
fontSize: '16px'
},
pointFormat: '{series.name}<br><span style="font-size:2em; color: {point.color}; font-weight: bold">{point.y}%</span>',
positioner: function (labelWidth, labelHeight) {
return {
x: 200 - labelWidth / 2,
y: 180
};
}
},
pane: {
startAngle: 0,
endAngle: 360,
background: [{ // Track for Move
outerRadius: '112%',
innerRadius: '88%',
backgroundColor: Highcharts.Color(Highcharts.getOptions().colors[0]).setOpacity(0.3).get(),
borderWidth: 0
}, { // Track for Exercise
outerRadius: '87%',
innerRadius: '63%',
backgroundColor: Highcharts.Color(Highcharts.getOptions().colors[1]).setOpacity(0.3).get(),
borderWidth: 0
}, { // Track for Stand
outerRadius: '62%',
innerRadius: '38%',
backgroundColor: Highcharts.Color(Highcharts.getOptions().colors[2]).setOpacity(0.3).get(),
borderWidth: 0
}]
},
yAxis: {
min: 0,
max: 100,
lineWidth: 0,
tickPositions: []
},
plotOptions: {
solidgauge: {
borderWidth: '34px',
dataLabels: {
enabled: false
},
linecap: 'round',
stickyTracking: false
}
},
series: []
};
var gauge1;
$.getJSON('bryan.json', function(json){
console.log(json)
options.chart.renderTo = 'container';
options.series.data = json
gauge1 = new Highcharts.Chart(options);
});
/**
* In the chart load callback, add icons on top of the circular shapes
*/
function callback()
{
// Move icon
this.renderer.path(['M', -8, 0, 'L', 8, 0, 'M', 0, -8, 'L', 8, 0, 0, 8])
.attr({
'stroke': '#ffffff',
'stroke-linecap': 'round',
'stroke-linejoin': 'round',
'stroke-width': 2,
'zIndex': 10
})
.translate(190, 26)
.add(this.series[2].group);
// Exercise icon
this.renderer.path(['M', -8, 0, 'L', 8, 0, 'M', 0, -8, 'L', 8, 0, 0, 8, 'M', 8, -8, 'L', 16, 0, 8, 8])
.attr({
'stroke': '#ffffff',
'stroke-linecap': 'round',
'stroke-linejoin': 'round',
'stroke-width': 2,
'zIndex': 10
})
.translate(190, 61)
.add(this.series[2].group);
// Stand icon
this.renderer.path(['M', 0, 8, 'L', 0, -8, 'M', -8, 0, 'L', 0, -8, 8, 0])
.attr({
'stroke': '#ffffff',
'stroke-linecap': 'round',
'stroke-linejoin': 'round',
'stroke-width': 2,
'zIndex': 10
})
.translate(190, 96)
.add(this.series[2].group);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="container" style="width: 400px; height: 400px; margin: 0 auto">
</div>
And here is my json data which i thout might be rendered but it didnot.
data.json
First of all, instead of options.series.data = json, you need to create the first series and then populate its data array with your data. Also, set in each point different radius and innerRadius properties. Take a look at the example below.
API Reference:
http://api.highcharts.com/highcharts/series.solidgauge.data.radius
http://api.highcharts.com/highcharts/series.solidgauge.data.innerRadius
Example:
http://jsfiddle.net/x3cne1ng/

Stacked bar chart from JSON file - seems to be ignoring a value

Pretty new to this stuff, so any help is greatly appreciated. To start off with, here is my JSON file's contents:
[
{
"drg": "NONSPECIFIC CEREBROVASCULAR DISORDERS W MCC",
"approved": 124,
"denied": 38
},
{
"drg": "SEIZURES WO MCC",
"approved": 138,
"denied": 26
},
{
"drg": "CHRONIC OBSTRUCTIVE PULMONARY DISEASE W CC",
"approved": 352,
"denied": 61
},
{
"drg": "CHEST PAIN",
"approved": 246,
"denied": 44
},
{
"drg": "TRANSIENT ISCHEMIA",
"approved": 205,
"denied": 37
},
{
"drg": "OTHER DISORDERS OF NERVOUS SYSTEM W CC",
"approved": 133,
"denied": 23
},
{
"drg": "DIABETES W MCC",
"approved": 151,
"denied": 27
},
{
"drg": "CARDIAC ARRHYTHMIA CONDUCTION DISORDERS W CC",
"approved": 336,
"denied": 55
},
{
"drg": "HYPERTENSION WO MCC",
"approved": 177,
"denied": 29
},
{
"drg": "POISONING TOXIC EFFECTS OF DRUGS WO MCC",
"approved": 144,
"denied": 24
}
]
My stacked bar chart, which worked fine with a CSV file, keeps ignoring the "denied" value. I suspect the issue has something to do with my formatting of the "processed_json.push()" portion of my code. It renders the approved value stacked on top of itself. Here is the script file:
<script>
$(document).ready(function() {
var processed_json = new Array();
$.getJSON('/dashboard-test-data/denied-percentage-2015-chart.json', function(data) {
for (i = 0; i < data.length; i++) {
processed_json.push([data[i].drg, data[i].approved, data[i].denied]);
}
$('#denied-percentage-2015-chart').highcharts({
chart: {
type: 'bar'
},
credits: {
text: 'Vortext Analytics',
href: 'http://www.vortextanalytics.com'
},
title: {
text: 'Top 10 DRG by Denial Percentage 2015'
},
xAxis: {
type: 'category',
},
navigation: {
menuStyle: {
border: '1px solid #ddd',
boxShadow: 'none',
},
menuItemStyle: {
padding: '5px 1.5rem',
},
menuItemHoverStyle: {
backgroundColor: '#f7f7f9',
color: '#666'
},
buttonOptions: {
height: 40,
width: 46,
symbolX: 23,
symbolY: 22,
x: 10,
y: -15,
symbolSize: 13,
}
},
yAxis: {
min: 0,
title: {
text: 'Total Records'
},
stackLabels: {
enabled: true,
style: {
fontWeight: 'bold',
color: (Highcharts.theme && Highcharts.theme.textColor) || 'gray'
},
formatter: function() {
return (this.axis.series[1].yData[this.x] / this.total * 100).toPrecision(2) + '%';
}
}
},
legend: {
align: 'left',
x: 0,
verticalAlign: 'bottom',
y: 22,
floating: true,
backgroundColor: (Highcharts.theme && Highcharts.theme.background2) || 'white',
borderColor: '#CCC',
borderWidth: 1,
shadow: false,
reversed: true,
},
tooltip: {
shared: true,
pointFormat: '<span style="color:{point.color}">\u25CF</span> {series.name}: {point.y:,0f} of {point.stackTotal:,0f} <b>({point.percentage:.1f}%)</b><br />',
},
plotOptions: {
series: {
stacking: 'normal',
dataLabels: {
enabled: true,
color: (Highcharts.theme && Highcharts.theme.dataLabelsColor) || 'white',
style: {
textOutline: 'none',
fontWeight: 'normal',
fontSize: '9px'
}
},
pointWidth: 20,
}
},
series: [{
name: 'approved',
color: '#55B4E4',
data: processed_json,
}, {
name: 'denied',
color: '#005079',
data: processed_json,
}],
});
});
});
</script>
Here is what the end product should produce (screen grab from my csv version):
Correct
And here is what I'm getting from the JSON file: incorrect
Any assistance or guidance is greatly appreciated. Thanks.
Have a look at highchart's stacked bar chart example. For each series, data contains the array of values for that series.
series: [{
name: 'John',
data: [5, 3, 4, 7, 2]
}, {
name: 'Jane',
data: [2, 2, 3, 2, 1]
}, {
name: 'Joe',
data: [3, 4, 4, 2, 5]
}]
In your case, instead of creating the processed_json array of objects, you should create separate arrays containing each series' values.
Change the loop this way:
var xAxis = []
, approvedCount = []
, deniedCount = []
for (i = 0; i < data.length; i++) {
xAxis.push(data[i].drg);
approvedCount.push(data[i].approved);
deniedCount.push(data[i].denied);
Then adapt the chart's instantiation accordingly:
// (...)
xAxis: {
categories: xAxis
},
// (...)
series: [{
name: 'approved',
color: '#55B4E4',
data: approvedCount,
}, {
name: 'denied',
color: '#005079',
data: deniedCount,
}],
// (...)

populating x-axis(Category) Highcharts ajax

I need assistance on how to dynamically bind my x-axis. I have written a webservice, that will fetch the data from the stored procedure.
I am stuck on displaying just the first column from the SP as for the x-axis.
$.ajax({
type: "POST",
url: "/path/path.asmx/xpath",
contentType: 'application/json; charset=utf-8',
dataType: "json",
success: function(data) {
alert("X_axis function is being hit")
// Parse JSON data:
var jsonCategories = eval('(' + data + ')');
alert(jsonCategories);
// Pass parsed data to the chart:
$('#Div3').xAxis[0].setCategories(jsonCategories);
}
})
// };
$('#Div3').highcharts({
chart: {
type: 'areaspline',
backgroundColor: {
linearGradient: { x1: 0, y1: 0, x2: 1, y2: 1 },
stops: [
[0, '#2a2a2b'],
[1, '#3e3e40']
]
}
},
title: {
text: 'Average Disc Space consumption',
style: { fontSize: 10, color: '#E0E0E3' }
},
legend: {
layout: 'vertical',
align: 'right',
verticalAlign: 'top',
x: 0,
y: 0,
floating: true,
borderWidth: 1,
backgroundColor: (Highcharts.theme && Highcharts.theme.legendBackgroundColor) || '#EEE'
},
legend: {
enabled: true
},
xAxis: {
categories: [],
labels: {
style: {
color: '#E0E0E3'
}
},
plotBands: [{
from: 4.5,
to: 6.5,
color: 'rgba(68, 170, 213, .2)'
}]
},
yAxis: {
title: {
text: 'Disc (GB)',
style: { fontSize: 10, color: '#E0E0E3' }
},
labels: {
style: {
color: '#E0E0E3'
}
}
},
tooltip: {
shared: true,
valueSuffix: ' GB'
},
credits: {
enabled: false
},
plotOptions: {
areaspline: {
fillOpacity: 0.5
}
},
series: [{
name: 'DB size',
data: [20, 10, 65, 3, 55, 62, 58]
}, {
name: 'Data size',
data: [19, 34, 47, 31, 3, 54, 41]
},
{
name: 'Log size',
data: [11, 34, 49, 38, 38, 80, 10]
},
{
name: 'Backup size',
data: [1, 32, 47, 3, 39, 59, 4]
}
]
});

Highchart speedometer take input from csv

I am trying to read the data from csv and display it as a input to Speedometer but I am unable to get the chart. Please tell me where i am going wrong.
My code is:
$(document).ready(function() {
var options = {
chart: {
type: 'gauge',
plotBackgroundColor: null,
plotBackgroundImage: null,
plotBorderWidth: 0,
plotShadow: false
},
title: {
text: 'Speedometer'
},
pane: {
startAngle: -150,
endAngle: 150,
background: [{
backgroundColor: {
linearGradient: { x1: 0, y1: 0, x2: 0, y2: 1 },
stops: [
[0, '#FFF'],
[1, '#333']
]
},
borderWidth: 0,
outerRadius: '109%'
}, {
backgroundColor: {
linearGradient: { x1: 0, y1: 0, x2: 0, y2: 1 },
stops: [
[0, '#333'],
[1, '#FFF']
]
},
borderWidth: 1,
outerRadius: '107%'
}, {
// default background
}, {
backgroundColor: '#DDD',
borderWidth: 0,
outerRadius: '105%',
innerRadius: '103%'
}]
},
// the value axis
yAxis: {
min: 0,
max: 100,
minorTickInterval: 'auto',
minorTickWidth: 1,
minorTickLength: 10,
minorTickPosition: 'inside',
minorTickColor: '#666',
tickPixelInterval: 30,
tickWidth: 2,
tickPosition: 'inside',
tickLength: 10,
tickColor: '#666',
labels: {
step: 2,
rotation: 'auto'
},
title: {
text: 'km/h'
},
plotBands: [{
from: 0,
to: 120,
color: '#55BF3B' // green
}, {
from: 120,
to: 160,
color: '#DDDF0D' // yellow
}, {
from: 160,
to: 200,
color: '#DF5353' // red
}]
},
series: []
};
$.get('data.csv', function(data) {
var series = {
data: [],
name: 'Speed',
tooltip: {
valueSuffix: ' km/h'
}
};
series.data.push(parseFloat(data));
options.series.push(series);
alert("data "+options.series);
var chart = new Highcharts.Chart(options);
});
});
and the csv file is simple
data.csv has only one value 30.
or incase it is
t1,30
t2,40
t3,60
how do i display 3 corresponding speedometers with respective speed.
Your help is greatly appreciated.
Thanks in advance.
In your case data your data (from ajax) is a single string, but you need to split elements and then choose which should be parsed to integer (parseFloat).