I currently have an array of data that I am trying to display on Highcharts.
const data = [10,31,13,19,21]
I am having issues with displaying a specific index of an array. For example, I would like one column to be data: data[0] the other data: data[1] etc.. When doing this I do not have any data displaying on my graph.
I am able to display data when doing data:data and displaying the whole array which creates multiple columns but for my situation, like to keep each point in one column.
Here is a link to a jsfiddle
desired look with specific index of an array i.e. data: data[1]:
outcome if using data: data
here is my code:
const data = [10,31,13,19,21]
Highcharts.chart('container', {
chart: {
type: 'bar'
},
title: {
text: "Bar Graph"
},
xAxis: {
},
yAxis: {
min: 0,
formatter: function () {
return this.value + "%";
},
title: {
text: '% of Total'
}
},
legend: {
reversed: false
},
plotOptions: {
series: {
stacking: 'normal'
}
},
series: [{
name: 'Low',
data: data[0],
showInLegend: false,
},{
name: 'Low',
data: data[1]
},{
name: 'Medium-Low',
data: data[2]
}, {
name: 'Medium',
data: data[3]
}, {
name: 'Medium-High',
data: data[4]
}, {
name: 'High',
data: data[5]
}
]
});
The data must be an array, meanwhile data[0], data[1], ... are numbers. Instead, you need to assign those values in the array, like: data: [data[1]].
Demo: https://jsfiddle.net/BlackLabel/ty42b0hs/
series: [{
name: 'Low',
color: '#0D6302',
data: [data[0]],
showInLegend: false,
},{
name: 'Low',
color: '#0D6302',
data: [data[1]]
}, ...]
Related
this is my first time posting here, so I apologize in advanced if I missed something I needed to include.
I am trying to create a donut chart with data from a php file, and even though the array loads and is visible in the console log, the following error is shown.
Failed to create chart: can't acquire context from the given item
<div id="trafficChart" style="min-height: 400px;" class="echart"></div>
<script>
var Name = [];
var Q_Sold = [];
$(document).ready(function(){
$.ajax({
url: "https://host-3:8890/data.php",
method: "GET",
success: function(data) {
console.log(data);
Name = [];
Q_Sold = [];
for(var i in data) {
Name.push(data[i].Name);
Q_Sold.push(data[i].Q_Sold);
}
},
error: function(data) {
console.log(data);
}
});
});
document.addEventListener("DOMContentLoaded", () => {
echarts.init(document.querySelector("#trafficChart")).setOption({
tooltip: {
trigger: 'item'
},
legend: {
top: '5%',
left: 'center'
},
series: [{
name: 'Access From',
type: 'pie',
radius: ['40%', '70%'],
avoidLabelOverlap: false,
label: {
show: false,
position: 'center'
},
emphasis: {
label: {
show: true,
fontSize: '18',
fontWeight: 'bold'
}
},
labelLine: {
show: false
},
data: [{
value: Q_Sold,
name: Name
}]
}],
});
});
</script>
</div>
</div>
However if I change the data values from
data: [{
value: Q_Sold,
name: Name
}]
To
data: [{
value: 1000,
name: "Name"
}]
The Chart renders perfectly fine. I have no clue to what the problem might be.
I am trying to parse a piechart out of an json-object which I get by calling an API. I want to use a specific key-value pair for rendering of the piechart itself.
I then want to use some other key-value results in my tooltips.
Imagine the following scenario which works so far.
const labels = [
'Januar',
'Februar'
];
const data = {
labels: labels,
datasets: [{
label: 'My First dataset',
backgroundColor: ["#0074D9", "#FF4136"],
data: [req('url').current_price.eur, req('url').current_price.eur],
}]
const config = {
type: 'pie',
data: data,
options: {
responsive: true,
plugins: {
tooltip: {
enabled: true,
usePointStyle: true,
callbacks: {
title: function(tooltipItem, data) {
console.log(tooltipItem);
return "Index " + tooltipItem[0].label;
},
label: (context) => {
console.log('context', context);
return 'test'
}
},
},
},
},
};
const myChart = new Chart(
document.getElementById('myChart'),
config
);
<html>
<meta charset="UTF-8">
<div>
<canvas id="myChart"></canvas>
</div>
</html>
So what I'm trying, is calling the API in data without the keys, so that I can access the object in context and use some of this values in my label for example.
I found the
parsing: {
yAxisKey: 'current_price.eur'
}
config but this isn't working for me if I change everything according to my idea, so that it renders the current_price.eur values
For pie/doughnut charts you need to specify the key option since it doesnt use any axes. So if you make your object like (together with latest version, 3.6.0) this it should work:
parsing: {
key: 'current_price.eur'
}
Example of object pie chart:
var options = {
type: 'doughnut',
data: {
datasets: [{
label: '# of Votes',
data: [{
id: 'parent1',
key: 55
}, {
id: 'parent2',
key: 55
}, {
id: 'paren3',
key: 30
}],
},
{
label: '# of Points',
data: [{
id: 'child1',
key: 55
}, {
id: 'child2',
key: 55
}, {
id: 'child3',
key: 30
}, {
id: 'child4',
key: 55
}, {
id: 'child5',
key: 55
}, {
id: 'child6',
key: 30
}],
}
]
},
options: {
plugins: {
tooltip: {
callbacks: {
label: (ttItem) => (`${ttItem.raw.id}: ${ttItem.raw.key}`)
}
}
},
parsing: {
key: 'key'
}
}
}
var ctx = document.getElementById('chartJSContainer').getContext('2d');
new Chart(ctx, options);
<body>
<canvas id="chartJSContainer" width="600" height="400"></canvas>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.6.0/chart.js"></script>
</body>
I want to show the user about which nodes are some sort of type in network graph of Highchart JS.
For example, the red node would be about "car" and the black node would be about "person".
How can I implement such a legend in Highchart Js?
Here is my codepen.
Highcharts.seriesTypes.networkgraph.prototype.drawLegendSymbol = Highcharts.LegendSymbolMixin.drawRectangle;
Highcharts.chart('container', {
chart: {
type: 'networkgraph'
},
plotOptions: {
networkgraph: {
keys: ['from', 'to']
}
},
legend: {
enabled: true
},
series: [{
showInLegend: true,
data: [
['A', 'B'],
['C','D'],
['E','F']
],
nodes:[{
id:'A',
color:'#ff1000'
},{
id:'B',
color:'#222222'
},
{
id:'C',
color:'#ff1000'
},
{
id:'D',
color:'#222222'
},
{
id:'E',
color:'#ff1000'
},
{
id:'F',
color:'#222222'
},]
}]
});
Thank you in advance.
Have you tried adding the dataLabel to series property and add a name to your nodes.
{
id: "A",
color: "#ff1000",
name: "car" <--------- name property
},
Something like this:
series: {
dataLabels: {
linkFormat: '',
enabled: true,
format: "{point.name}",
crop: false,
defer: false,
useHtml: true,
},
}
Full example:
https://codepen.io/tiagotedsky/pen/zYZYOLR
I am using HighCharts to make a graph with columns, drilldown series and scatter. The problem which I am having, is that the HighChart is created before the $.getJSON function is succesfully exicited. I have found several other articles, but non yet where two $.getJSON functions are called. The code which I am using:
$(function () {
// Create the chart
var options = {
chart: {
renderTo: 'container_genomefraction',
type: 'column',
events: {
// Declare the events changing when the drilldown is activated
drilldown: function(options) {
this.yAxis[0].update({
labels: {
format: '{value}'
},
title: {text : "Gbp"}
}, false, false);
options.seriesOptions.dataLabels = {
format: '{point.y:.1f}'
};
options.seriesOptions.tooltip = {
pointFormat: '<span style="color:{point.color}">{point.name}</span>: <b>{point.y:.2f}</b> of total<br/>'
};
},
// Declare the events changing when the drillup is activated
drillup: function () {
this.yAxis[0].update({
labels: {
format: '{value}%'
},
title: {text : "Percentages"}
}, false, false);
}
}
},
title: {
text: 'Comparison'
},
xAxis: {
type: 'category'
},
yAxis: [{
title: {
enabled: true,
text: 'Percentages',
style: {
fontWeight: 'normal'
}
},
labels: {
format: '{value}%'
}
},{
min: 0,
title :{
text : 'input'
},
labels: {
format : '{value}'
},
opposite: true
}],
legend: {
enabled: false
},
plotOptions: {
series: {
marker: {
fillColor: '#FFFFFF',
lineWidth: 2,
lineColor: null, // inherit from series
size : 50
},
borderWidth: 0,
dataLabels: {
enabled: true,
format: '{point.y:.1f}%'
}
}
},
tooltip: {
headerFormat: '<span style="font-size:11px">{series.name}</span><br>',
pointFormat: '<span style="color:{point.color}">{point.name}</span>: <b>{point.y:.2f}%</b> of total<br/>'
},
// Declare an empty series
series: [{
name: '',
colorByPoint: true,
data: []
}],
credits: {
enabled: false
},
// Declare an empty drilldown series
drilldown: {
series: [{
name : '',
id: '',
data: []
}]
}
};
// Your $.getJSON() request is now synchronous...
$.ajaxSetup({
async: false
});
// Get the input into one series
$.getJSON('/uploads/fraction.json', function (list) {
options.series = list;
});
// Get the drilldown estimated and total size into one series
$.getJSON('/uploads/drilldown.json', function (list2) {
options.drilldown.series = list2;
var chart = new Highcharts.Chart(options);
});
$.ajaxSetup({
async: true
});
});
My JSONs are formatted:
fraction.json
[{"name":"1","colorByPoint":true,"data":[{"name":1,"y":80,"drilldown":1},{"name":2,"y":87,"drilldown":2},{"name":3,"y":105.71428571429,"drilldown":3}]},{"name":"input","dataLabels":"{enabled,false}","yAxis":1,"type":"scatter","data":[{"y":38,"name":1,"drilldown":1},{"y":"","name":2,"drilldown":2},{"y":27,"name":3,"drilldown":3}],"tooltip":{"headerFormat":"<span style='font-size:11px'>{series.name}<\/span><br>","pointFormat":"<span style='color:{point.color}'>{point.name}<\/span>: <b>{point.y}<\/b><br\/>"}}]
drilldown.json
[{"name":1,"id":1,"data":[["Total",2],["Estimated",2.5]]},{"name":2,"id":2,"data":[["Total",3.9],["Estimated",4.5]]},{"name":3,"id":3,"data":[["Total",3.7],["Estimated",3.5]]}]
When the page is loaded, the graph displays the values of the previous search done and when I reload the page, the correct data is shown. Could someone please help me out?
Add the second getJSON method in the first getJSON success callback like this:
//Get the genome fraction into one series
$.getJSON('/uploads/fraction.json', function (list) {
options.series = list;
//Get the drilldown estimated and total genome size into one series
$.getJSON('/uploads/drilldown.json', function (list2) {
options.drilldown.series = list2;
var chart = new Highcharts.Chart(options);
});
});
i get my JSON object from my php code in this format (JSONlint ok) :
[
[1375653600000,3.20104,175.00,116.00,11.00,31.00],[...],[1376776800000,2.85625,10.00,1.00,0.00,8.00]
]
i Have to split in 5 different series:
[1375653600000, 3.201014]
[1375653600000, 175.00]
[1375653600000, 116.00]
[1375653600000, 11.00]
[1375653600000, 31.00]
...
and (obviously) each array is for a different highcharts series.
i follow this post to get an idea about split the JSON:
Retrieving JSON data for Highcharts with multiple series?
This is my code:
$(function() {
// See source code from the JSONP handler at https://github.com/highslide-software/highcharts.com/blob/master/samples/data/from-sql.php
$.getJSON('grafico_nuovo.php?callback=?', function(data) {
// Add a null value for the end date
data = [].concat(data, [[Date.UTC(2012, 9, 14, 19, 59), null, null, null, null]]);
// create the chart
$('#container').highcharts('StockChart', {
chart : {
type: 'spline',
zoomType: 'xy'
},
navigator : {
adaptToUpdatedData: false,
series : {
data : data
}
},
scrollbar: {
liveRedraw: false
},
title: {
text: 'analisi consumi e temperature'
},
subtitle: {
text: 'Analisi test solo temperatura media'
},
rangeSelector : {
buttons: [{
type: 'hour',
count: 1,
text: '1h'
}, {
type: 'day',
count: 2,
text: '2d'
}, {
type: 'week',
count: 1,
text: '1w'
},{
type: 'month',
count: 1,
text: '1m'
}, {
type: 'year',
count: 1,
text: '1y'
}, {
type: 'all',
text: 'All'
}],
inputEnabled: true, // it supports only days
selected : 2 // day
},
/*xAxis : {
events : {
afterSetExtremes : afterSetExtremes
},
minRange: 3600 * 1000 // one hour
},*/
xAxis: {
events : {
afterSetExtremes : afterSetExtremes
},
minRange: 3600 * 1000, // one hour
type: 'datetime',
dateTimeLabelFormats: { minute: '%H:%M', day: '%A. %e/%m' },
// minRange: 15*60*1000,
//maxZoom: 48 * 3600 * 1000,
labels: {
rotation: 330,
y:20,
staggerLines: 1 }
},
yAxis: [{ // Primary yAxis
labels: {
format: '{value}°C',
style: {
color: '#89A54E'
}
},
title: {
text: 'Temperature',
style: {
color: '#89A54E'
}
}
}, { // Secondary yAxis
title: {
text: 'Consumo',
style: {
color: '#4572A7'
}
},
labels: {
format: '{value} Kw',
style: {
color: '#4572A7'
}
},
opposite: true
}],
series: [{
name: 'val1',
data: []
}, {
name: 'val2',
data: []
},
{
name: 'val3',
data: []
},
{
name: 'val4',
data: []
},
{
name: 'val5',
data: []
}]
});
});
});
/**
* Load new data depending on the selected min and max
*/
function afterSetExtremes(e) {
var currentExtremes = this.getExtremes(),
range = e.max - e.min,
chart = $('#container').highcharts();
chart.showLoading('Loading data from server...');
$.getJSON('grafico_nuovo.php?start='+ Math.round(e.min) +
'&end='+ Math.round(e.max) +'&callback=?', function(data) {
val1 = [];
val2 = [];
val3 = [];
val4 = [];
val5 = [];
$.each(data, function(key,value) {
val1.push([value[0], value[1]]);
val2.push([value[0], value[2]]);
val3.push([value[0], value[3]]);
val4.push([value[0], value[4]]);
val5.push([value[0], value[5]]);
});
console.log('val1');
chart.series[0].setData(val1);
chart.series[1].setData(val2);
chart.series[2].setData(val3);
chart.series[3].setData(val4);
chart.series[4].setData(val5);
chart.hideLoading();
});
}
The navigator works fine (with little trouble after 3-4 clicks) but the other series doesn't show.
Everything should be ok, but i've probably missed something