I want to import my JSON file to Echarts to make a line chart but failed, the result page is totally blank. I search it in google but couldn't find a proper answer.
This is the JSON:
[
{ "category": "A", "value": 1 },
{ "category": "B", "value": 2 },
{ "category": "C", "value": 3 },
{ "category": "D", "value": 7 }
]
var dataArr = [];
var myChart = echarts.init(document.getElementById('demo'));
$.get('data.json', {}, function(response) {
dataArr = JSON.parse(response);
initEchart();
});
function initEchart() {
// specify chart configuration item and data
var option = {
title: {
text: 'entry example'
},
tooltip: {},
xAxis: {
type: 'category',
data: dataArr.category
},
yAxis: {},
series: [{
type: 'line',
data: dataArr.value
}]
};
myChart.setOption(option);
}
<script type='text/javascript' src='https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js'></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/echarts/4.7.0/echarts.min.js" integrity="sha256-eKrx6Ly6b0Rscx/PSm52rJsvK76RJyv18Toswq+OLSs=" crossorigin="anonymous"></script>
<div id="demo" style="width: 600px;height:400px;"></div>
Thank you for helping me solve this problem.
I fixed your version. You tried to pass to the chart empty data because key dataArr.category does not exist. You received array so need collect data with loop: dataArr.map(row => row['category']) and will be ok.
var dataArr = [];
var myChart = echarts.init(document.getElementById('demo'));
$.get('https://gist.githubusercontent.com/creadone/d15105b0c7e33848ef9559c28a9912c2/raw/64a17c5ac38b375cd6ab858d51a66836d9259ed0/data.json', {}, function(response) {
dataArr = JSON.parse(response);
console.log(dataArr);
initEchart();
});
function initEchart() {
// specify chart configuration item and data
var option = {
title: {
text: 'entry example'
},
tooltip: {},
xAxis: {
type: 'category',
data: dataArr.map(row => row['category'])
},
yAxis: {},
series: [{
type: 'line',
data: dataArr.map(row => row['value'])
}]
};
myChart.setOption(option);
}
<script type='text/javascript' src='https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js'></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/echarts/4.7.0/echarts.min.js" integrity="sha256-eKrx6Ly6b0Rscx/PSm52rJsvK76RJyv18Toswq+OLSs=" crossorigin="anonymous"></script>
<div id="demo" style="width: 600px;height:400px;"></div>
Related
I'm rendering a timeseries line graph using FusionCharts as follows:
const MyChart = () => {
const schema = [
{
name: "Category",
type: "string"
},
{
name: "Time",
type: "date",
format: "%Y-%m-%d"
},
{
name: "Value",
type: "number"
}
]
const data = [
["CategoryToStyle", "2022-09-01", 5],
["CategoryToStyle", "2022-10-01", 10],
["Category2", "2022-09-01", 2],
["Category2", "2022-10-01", 7]
]
const dataStore = new FusionCharts.DataStore().createDataTable(data, schema);
const chartSettings = {
type: "timeseries",
dataSource: {
data: dataStore,
series: "Category",
yAxis: {
format: {
prefix: "$"
}
}
}
}
return <ReactFC width={1024} height={1024} {...chartSettings} />
}
The chart renders 2 line plots, one for the "CategoryToStyle" series and one for "Category2" series.
How can I customize the "stroke-width" of the line plot for the series "CategoryToStyle"?
I want to update a chart.
https://jsfiddle.net/q2hLgk9z/2/
the original idea comes from here:https://jsfiddle.net/wxzpk9dn/2/
<head>
<script src="https://cdn.jsdelivr.net/npm/apexcharts#3.18.1/dist/apexcharts.min.js"></script>
</head>
<div>
<input type="radio" id="columnGraph" name="graph" value="line" />
<label for="columnGraph">Line</label>
</div>
<div>
<input type="radio" id="barGraph" name="graph" value="line1" checked />
<label for="barGraph">Barra</label>
</div>
<div id="chartwind" ></div> </pre>
and script
<script>
// CHART OPTIONS by chart type
let chartOptions = {
line1: {
chart: { type: "line" },
series: [
{ name: "One", type: "line", data: [15, 20] },
{ name: "Two", type: "line", data: [30, 25] },
],
labels: ["2017", "2018"],
stroke: { width: 2 },
},
line: {
chart: { type: "line" },
series: [
{ name: "2017", type: "line", data: [65, 20] },
{ name: "2018", type: "line", data: [15, 25] },
],
labels: ["from", "to"],
stroke: { width: 5 },
},
};
//select the radiobuttons
var chartTypeControlButtons = document.querySelectorAll(
'input[type=radio][name="graphicType"]'
),
chartTypeControlButtonInitChecked = document.querySelectorAll(
'input[type=radio][name="graphicType"]:checked'
);
// Chart type changing (HANDLER)
//switch between the graphs
function changeHandler(event) {
let selectedChartType = this.value,
updatedChartOptions = chartOptions[selectedChartType];
chart.updateOptions(updatedChartOptions);
}
//Listener for the radios
Array.prototype.forEach.call(chartTypeControlButtons, function (radio) {
radio.addEventListener("change", changeHandler);
});
// Render the chart with initial options and then
let initialChartType = chartTypeControlButtonInitChecked[0].value,
// think of it as a preparing the ground
// USE 'bar' as the type. If you choose 'pie' ... you will get glithes
initialChartOptions = {
chart: {
width: 350,
type: "line",
},
series: [],
};
// Create chart with init options
// Note that the link to the chart object is in the GLOBAL scope
var chart = new ApexCharts(
document.getElementById("chartwind"),
initialChartOptions
);
chart.render(); // Firstly, prepare the ground
chart.updateOptions(chartOptions[initialChartType]); // Secondly, draw we want
</script>
<div id="chartwind"></div>
</body>
In Jsfiddle it is working but not an my PC.
I load the apexchartversion as fiddle (3.18.1) - but this does not matter.^It is the same issue with the latest version.
I get 2 errormessages:
in the start: after chart.render:Uncaught (in promise) Error: Element not found (maybe because series ist []. But it does not change with values.
then in the update mode: Uncaught TypeError: Cannot read property 'filter' of undefined
Do you have an idea, what I can try on my machine? (I have the same issue on different browsers).
Maybe you have an idea about the difference to fiddle?
Just define your script file path after your <div id="chartwind"></div>.
It will work.
Example:
index.html
<head>
<script src="https://cdn.jsdelivr.net/npm/apexcharts#3.18.1/dist/apexcharts.min.js"></script>
</head>
<div>
<input type="radio" id="columnGraph" name="graph" value="line" />
<label for="columnGraph">Line</label>
</div>
<div>
<input type="radio" id="barGraph" name="graph" value="line1" checked />
<label for="barGraph">Barra</label>
</div>
<div id="chartwind" ></div>
<script src="./apex.js"></script>
apex.js
let chartOptions = {
line1: {
chart: {
type: "line"
},
series: [{
name: "One",
type: "line",
data: [15, 20]
},
{
name: "Two",
type: "line",
data: [30, 25]
},
],
labels: ["2017", "2018"],
stroke: {
width: 2
},
},
line: {
chart: {
type: "line"
},
series: [{
name: "2017",
type: "line",
data: [65, 20]
},
{
name: "2018",
type: "line",
data: [15, 25]
},
],
labels: ["from", "to"],
stroke: {
width: 5
},
},
};
var chartTypeControlButtons = document.querySelectorAll(
'input[type=radio][name="graph"]'
),
chartTypeControlButtonInitChecked = document.querySelectorAll(
'input[type=radio][name="graph"]:checked'
);
//console.log("checked", chartTypeControlButtonInitChecked.length);
//console.log("radios", chartTypeControlButtons.length);
function changeHandler(event) {
let selectedChartType = this.value,
updatedChartOptions = chartOptions[selectedChartType];
//console.log("change");
chart.updateOptions(updatedChartOptions);
}
Array.prototype.forEach.call(chartTypeControlButtons, function(radio) {
radio.addEventListener("change", changeHandler);
});
// Render the chart with initial options and then
// you can update it with ANY wished options
// let initialChartType = $(chartTypeControlButtonInitChecked).val(),
//console.log("text", chartTypeControlButtonInitChecked[0].value);
let initialChartType = chartTypeControlButtonInitChecked[0].value,
// think of it as a preparing the ground
// USE 'bar' as the type. If you choose 'pie' ... you will get glithes
initialChartOptions = {
chart: {
width: 350,
type: "line",
},
labels: ["from", "to"],
stroke: {
width: 2
},
series: [],
};
// Create chart with init options
// Note that the link to the chart object is in the GLOBAL scope
var chart = new ApexCharts(
document.getElementById("chartwind"),
initialChartOptions
);
//console.log("initialChartType", initialChartType);
chart.render(); // Firstly, prepare the ground
//console.log(chartOptions[initialChartType]);
chart.updateOptions(chartOptions[initialChartType]); // Secondly, draw we want
// chart.updateOptions(newOptions); Redraw we want
I'm trying to display the data from my json.
My json file looks like this:
0: {OGS: "26", STRM: "1811", ACAD_CAREER: null, YEAR: "2018"}1: {OGS: "4144", STRM: "1801", ACAD_CAREER: null, YEAR: "2018"}2: {OGS: "3935", STRM: "1802", ACAD_CAREER: null, YEAR: "2018"}3: {OGS: "16", STRM: "1812", ACAD_CAREER: null, YEAR: "2018"}length: 4__proto__: Array(0)
And here's my code:
<script>
$(function () {
var categData = [];
var statusACountData = [];
var statusBCountData = [];
var dateVal=[];
var statusVal=[];
var countVal = [];
var jsonvar = [];
$.getJSON('http://localhost:37590/get_OGSDataPerTermYear/ORT/2018', function (jsonData) {
for(i=0;i<jsonData.length;i++){
dateVal[i]=jsonData[i].STRM;
// statusVal[i]=jsonData[i].status;
countVal[i]=jsonData[i].OGS;
}
// jsonData
console.log(jsonData);
console.log(countVal);
console.log(categData);
// $(function () {
Highcharts.chart('container', {
chart: {
type: 'column'
},
xAxis: {
categories: dateVal,
crosshair: true
},
series: [{
name: dateVal,
data: countVal
}]
});
// });
});
});
</script>
The column is not showing and the 4 data which is: 1801 1802 1803 and 1804 only appears in 1 series. I want to make them each series with different data which is OGS number.
To make it as you expect (each column is a separate series) you can follow this approach:
Prepare series and xAxis.categories arrays. Each series.data array should have an appropriate amount of null points before the one with real value. Something like that:
categories:
["1811", "1801", "1802", "1812"]
series:
[{
name: "cat - 0",
data: [2456]
}, {
name: "cat - 1",
data: [null, 4144]
}, {
name: "cat - 2",
data: [null, null, 3935]
}, {
name: "cat - 3",
data: [null, null, null, 2316]
}]
plotOptions.column.grouping should be disabled:
Highcharts.chart('container', {
chart: {
type: 'column'
},
xAxis: {
crosshair: true,
categories: categories
},
plotOptions: {
column: {
grouping: false
}
},
series: series
});
Demo:
https://jsfiddle.net/BlackLabel/ynqjftLk/
API reference:
https://api.highcharts.com/highcharts/plotOptions.column.grouping
enter image description hereYour data is not in right format. If you need to plot STRM is x axis , you will need to put them in a separate array and assign it to xAxis.
The yAxis also accepts an array of objects and the object need to have two keys like name & data where data is an array .
Also OGS values are in string , so adding a + before jsonData[i].OGS will convert it to number.
let jsonData = [{
OGS: "2456",
STRM: "1811",
ACAD_CAREER: null,
YEAR: "2018"
}, {
OGS: "4144",
STRM: "1801",
ACAD_CAREER: null,
YEAR: "2018"
}, {
OGS: "3935",
STRM: "1802",
ACAD_CAREER: null,
YEAR: "2018"
}, {
OGS: "2316",
STRM: "1812",
ACAD_CAREER: null,
YEAR: "2018"
}]
var categData = [];
var statusACountData = [];
var statusBCountData = [];
var dateVal = [];
var statusVal = [];
var countVal = [];
var jsonvar = [];
for (let i = 0; i < jsonData.length; i++) {
dateVal[i] = jsonData[i].STRM;
countVal.push({
name: 'someText',
data: [+jsonData[i].OGS]
})
}
Highcharts.chart('container', {
chart: {
type: 'column'
},
title: {
text: 'Some Text'
},
subtitle: {
text: 'someTExt'
},
xAxis: {
categories: dateVal,
crosshair: true
},
yAxis: {
min: 0,
title: {
text: 'OGS'
}
},
tooltip: {
headerFormat: '<span style="font-size:10px">{point.key}</span><table>',
footerFormat: '</table>',
shared: true,
useHTML: true
},
plotOptions: {
column: {
pointPadding: 0.2,
borderWidth: 0
}
},
series: countVal
});
<script src="https://code.highcharts.com/highcharts.js"></script>
<script src="https://code.highcharts.com/modules/exporting.js"></script>
<script src="https://code.highcharts.com/modules/export-data.js"></script>
<div id="container" style="min-width: 310px; height: 400px; margin: 0 auto"></div>
can you guys check my code for drilldown? it only display 1 data series right after i clicked the column on the first chart,.
$.getJSON('http://localhost:37590/get_OGSDataPerTermYear/' + strCampus + "/" +
data[i].YEAR, function (jsonDataDrill) {
const datadrill = jsonDataDrill
console.log(jsonDataDrill);
for (d = 0; d < datadrill.length; d++) {
categories = datadrill[d].STRM
dataseries.push({
id: datadrill[d].YEAR,
name: +datadrill[d].STRM,
data: [{
y: +datadrill[d].OGS
}]
})
}
});
I wan't to change series type, but
there is an javascript console error:
options.series in function change_chart is null...
<script src="../code/highstock.js"></script>
<div id="container" style="height: 400px; min-width: 310px"></div>
<script type="text/javascript">
var chart;
var options;
$(document).ready(function() {
options = {
chart: { renderTo: 'container'},
rangeSelector: {selected: 1},
title: { text: 'AAPL Stock Price'},
series: [{
type: 'candlestick',
name: 'AAPL Stock Price11',
dataGrouping: {
units: [
[
'week', // unit name
[1] // allowed multiples
], [
'month',
[1, 2, 3, 4, 6]
]
]
}
}]
};
chartfunc = function(type)
{
alert(options.series);
options.type = type;
chart = new Highcharts.stockChart(options);
}
$.getJSON('http://localhost/highstock/data/aapl-ohlcv.json', function(data) {
options.series[0].data = data;
chart = new Highcharts.stockChart(options);
});
});
</script>
I don't understand why options.series "sets itself" to null...
I got it working by changing chartfunc like this:
chartfunc = function(type)
{
chart.series[0].update({
type: type
});
}
So without jquery I want to update highcharts with new data live. I have a chart that displays data from a database, and I am doing a http get request to get the data every few seconds. I am able to grab the data correctly, but when I push the new data onto the series variable for the chart, the graph doesn't update in real time. It only updates when I refresh. How can I fix this? I am using highcharts in angularjs.
you should call series.addPoint() instead of just updating the data array
please see here http://jsfiddle.net/9m3fg/1
js:
var myapp = angular.module('myapp', ["highcharts-ng"]);
myapp.controller('myctrl', function ($scope) {
$scope.addPoints = function () {
var seriesArray = $scope.chartConfig.series
var newValue = Math.floor((Math.random() * 10) + 1);
$scope.chartConfig.xAxis.currentMax++;
//if you've got one series push new value to that series
seriesArray[0].data.push(newValue);
};
$scope.chartConfig = {
options: {
chart: {
type: 'line',
zoomType: 'x'
}
},
series: [{
data: [10, 15, 12, 8, 7, 1, 1, 19, 15, 10]
}],
title: {
text: 'Hello'
},
xAxis: {
currentMin: 0,
currentMax: 10,
minRange: 1
},
loading: false
}
});
From your code it looks like you want to add new series rather then new data if yes please see here: http://jsfiddle.net/bYx4a/
var app = angular.module('app', ["highcharts-ng"]);
app.controller("myCtrl", ['$scope', '$http', function ($scope, $http) {
var count = 0;
$scope.chartOptions = {
chart: {
type: 'line'
},
title: {
text: 'Fruit Consumption'
},
xAxis: {
categories: ['Apples', 'Bananas', 'Oranges']
},
yAxis: {
title: {
text: 'Fruit eaten'
}
},
series: [{
name: 'Jane',
data: [1, 0, 4]
}]
};
$scope.addSeries = function () {
var newData = {
name: 'John',
data: [1, 4, 3]
};
$scope.chartOptions.series.push({
name: newData.name,
data: newData.data
})
};
}]);
Here is my solution for using Highcharts addPoint function in the highcharts-ng directive:
$scope.chart_realtimeForceConfig = {
options: {
chart: {
type: 'line',
},
plotOptions: {
series: {
animation: false
},
},
},
series: [
{
name: 'Fx',
data: []
},
],
func: function(chart) {
$timeout(function() {
chart.reflow();
$scope.highchart = chart;
}, 300);
socket.on('ati_sensordata', function(data) {
if (data) {
var splited = data.split('|');
if (splited.length >= 6) {
var val = parseFloat(splited[5]);
var shift = chart.series[0].data.length > 100;
chart.series[0].addPoint(val, true, shift, false);
}
}
});
},
loading: false
}