Related
I'm using html, css and javascript for the project. The server is set up locally including node, express and highcharts.
In my html i have a div container, that i'm referencing in my highcharts function. The data i'm using in the highchart come from a csv file. I wrote a simple getData function, that parses the data into an array. And at the top of the highchartsfunction, i'm using await getData, so the chart can only be rendered after getting the data for it. All functions are async. On that one page i'm having seven charts, all constructed using the syntax following below, each with its own getData function and div container.
Two problems:
Problem No.1:
The charts are not getting displayed until i refresh the page and often times i even have to refresh it several times, till every chart is getting shown at a time (Like 20 times). The functions are all executed, i checked that in the console.
Problem No.2:
I would like to write this dynamically, as i want to have multiple pages on my website, each using its own csv file, but basically the same code.
*Edit:
From time to time i receive: "Error: Highcharts error #13: www.highcharts.com/errors/13/" in the console, but as i keep refreshing it changes the line/js it is referencing to. It always is the part of the highcharts function, in which i give it its container Highcharts.chart('hammerchart', {. I checked this error and what it sais is basically, that the script can't find a container with the #id. Which i don't understand as im using "DOMContentLoaded". I tried the "load" event instead, which solved the error #13, but ended up in no chart getting displayed at all without any error message.
*Edit2:
Until now i only used firefox to view my website. I checked Chrome aswell and here i don't have any error message, but it also never shows any of the charts aswell at all.
If someone could help me out here, i would be really happy, as i tried to fix this for days now with no success. I'm also open for suggestions, regarding the handling of my data. Thank you veeeery much in advance!!
Code:
CSV Data sample
2015,2.5,7.2,1.6,6.5,2.2
2016,3.5,7.6,2.6,9.3,1.2
2017,2.5,7.2,1.6,6.5,2.2
2018,3.5,7.6,2.6,9.3,1.2
2019,2.5,7.2,1.6,6.5,2.2
HTML
<div id="hammerchart">
</div>
CSS
#hammerchart{
width:49%;
height: 500px;
margin:0.5%;
margin-top:50px;
flex: 1 1 600px;
}
Javascript - first declaration of the arrays, then my parsing function, splitting the csv by linebreaks and commas. Then i'm using parseFloat(), so that i don't have strings in it. In the highcharts function i'm using await getData and DOMContentloaded, to make sure both html and my data are ready.
const years = [];
const columntwos = [];
const columnthrees = [];
const columnfours = [];
const columnfives = [];
const columnsixs = [];
async function getDataone() {
const response = await fetch('/javascripts/hammerchart.CSV');
const data = await response.text();
const table = data.split('\n');
table.forEach(row => {
const columns = row.split(',');
const year = columns[0];
years.push(year);
const columntwo = columns[1];
columntwos.push(parseFloat(columntwo));
const columnthree = columns[2];
columnthrees.push(parseFloat(columnthree));
const columnfour = columns[3];
columnfours.push(parseFloat(columnfour));
const columnfive = columns[4];
columnfives.push(parseFloat(columnfive));
const columnsix = columns[5];
columnsixs.push(parseFloat(columnsix));
});
};
async function hammerchart() {
await getDataone();
document.addEventListener('DOMContentLoaded', () => {
Highcharts.chart('hammerchart', {
chart: {
zoomType: 'xy'
},
title: {
text: 'Data'
},
subtitle: {
text: ''
},
credits: {
text: 'highcharts',
},
xAxis: [{
categories: years,
plotBands: [{ // visualize
from: 4.5,
to: 6,
color: 'rgba(68, 170, 213, .2)'
}],
crosshair: true
}],
yAxis: [{ // Primary yAxis
labels: {
format: '{value}$',
style: {
color: Highcharts.getOptions().colors[1]
}
},
title: {
text: 'Amount in $',
style: {
color: Highcharts.getOptions().colors[1]
}
}
}, { // Secondary yAxis
title: {
text: 'Ratio in %',
style: {
color: Highcharts.getOptions().colors[0]
}
},
labels: {
format: '{value} %',
style: {
color: Highcharts.getOptions().colors[0]
}
},
opposite: true
}],
tooltip: {
shared: true
},
legend: {
layout: 'vertical',
align: 'left',
x: 120,
verticalAlign: 'top',
y: 100,
floating: true,
backgroundColor:
Highcharts.defaultOptions.legend.backgroundColor || // theme
'rgba(255,255,255,0.25)'
},
series: [{
name: 'columntwo',
type: 'areaspline',
data: columntwos,
tooltip: {
valueSuffix: '$'
}
}, {
name: 'columnthree',
type: 'areaspline',
data: columnthrees,
tooltip: {
valueSuffix: '$'
}
}, {
name: 'columnfour',
type: 'areaspline',
data: columnfours,
tooltip: {
valueSuffix: '$'
}
}, {
name: 'columnfive',
type: 'column',
data: columnfives,
tooltip: {
valueSuffix: '$'
}
}, {
name: 'columnsix',
type: 'spline',
yAxis: 1,
data: columnsixs,
tooltip: {
valueSuffix: '%'
}
}]
});
});
};
hammerchart();
I am a bit out of my comfort zone, since I normally do analytics and not fancy front-ends. However, I would like to have a real-time demo of some of my work, so it becomes easier to understand and not just numbers in a matrix. I have looked around and found something semi-relevant and come this far:
(It has four series like I want to and it iterates - to some degree)
https://jsfiddle.net/023sre9r/
var series1 = this.series[0],
series2 = this.series[1],
series3 = this.series[2],
series4 = this.series[3];
But I am totally lost on how to remove the random number generators without loosing nice things like the number of data points in a view (seems to depend on the for loop?!). Remove the extra title "Values" right next to my real y-axis title. And of cause how to get a new data point from a XML-file every second.
Ideally I want to have an XML-file containing 4 values, which I update approximately every 200ms in MATLAB. And every second I would like my 4 series chart to update. Is it not relatively easy, if you know what you are doing?! :-)
Thanks in advance!
I simplified your example and added clear code showing how to fetch data from server and append it to your chart using series.addPoint method. Also if you want to use XML, just convert it to JS object / JSON.
const randomData = () => [...Array(12)]
.map((u, i) => [new Date().getTime() + i * 1000, Math.random()])
Highcharts.chart('container', {
chart: {
renderTo: 'container',
type: 'spline',
backgroundColor: null,
animation: Highcharts.svg, // don't animate in old IE
marginRight: 10,
events: {
load () {
const chart = this
setInterval(() => {
// Fetch example below (working example: https://github.com/stpoa/live-btc-chart/blob/master/app.js)
// window.fetch('https://api.cryptonator.com/api/ticker/btc-usd').then((response) => {
// return response.json()
// }).then((data) => {
// chart.series[0].addPoint({ x: data.timestamp * 1000, y: Number(data.ticker.price) })
// })
chart.series.forEach((series) => series.addPoint([new Date().getTime(), Math.random()], true, true))
}, 3000)
}
}
},
title: {
text: null
},
xAxis: {
type: 'datetime',
tickPixelInterval: 150
},
yAxis: [{
title: {
text: 'Temperature [°C]',
margin: 30
},
plotLines: [{
value: 0,
width: 1,
color: '#808080'
}]
}, {
}],
tooltip: {
formatter: function() {
return '<b>' + this.series.name + '</b><br/>' +
Highcharts.dateFormat('%Y-%m-%d %H:%M:%S', this.x) + '<br/>' + Highcharts.numberFormat(this.y, 4);
}
},
legend: {
enabled: true
},
exporting: {
enabled: false
},
rangeSelector: {
enabled: false
},
navigator: {
enabled: false
},
scrollbar: {
enabled: false
},
series: [{
name: 'Setpoint',
data: randomData()
}, {
name: 'Return',
data: randomData()
}, {
name: 'Supply',
data: randomData()
}, {
name: 'Output',
data: randomData()
}]
})
Live example: https://jsfiddle.net/9gw4ttnt/
Working one with external data source: https://jsfiddle.net/111u7nxs/
I am using Highcharts to automatically plot an array which is output from a sensor and is updated every second or so. The array is x elements long. This particular sensor measures the light intensity at x steps between some min and max wavelengths (that is, it measures the intensity at increments of (max-min)/x--in my case this increment is not an integer). I also have a static data set that is plotted on the same axes with the same x-axis requirements.
I am able to successfully graph this data dynamically, but the x-axis scale is wrong. Instead of ranging from min to max, Highcharts defaults to a range of min to min+x. I'd like to change the x-axis increment so that the scaling is correct.
Can a min, max, and number of data points or step be defined to generate the x-axis? Or is there a way to define the x- and y-axis values as individual arrays that are plotted against each other? Some other way? I have done lots of searching and experimenting but have come up short.
The relevant snippet of my code is below.
function showData(result) { // 'result' is an array that comes from the sensor
var numbers = int(split(resultString, ","));
chart.series[1].setData(numbers);
socket.send('a'); // send a byte to tell it to start sending new data
loop++; //increase loop every time the server receives data
chart.setTitle({ text: 'Spectrum, reading #' + loop });
} //showData
$(function () {
chart = new Highcharts.Chart({
chart: {
renderTo: 'container',
type: 'area',
load: function() {
chart = this;
showData();
}
},
title: {
text: 'Spectrum, reading 0'
},
xAxis: {
title: {
text: 'Wavelength [nm]',
allowDecimals: false,
},
},
yAxis: {
title: {
text: ''
},
},
tooltip: {
pointFormat: '{point.x}'
},
plotOptions: {
area: {
pointStart: 340,
marker: {
enabled: false,
symbol: 'circle',
radius: 2,
states: {
hover: {
enabled: true
}
}
}
}
},
series: [{
name: '404 nm laser spectrum',
data: [130,130,114,113,113,116,112,111,112,112,115,113,113,115,
112,114,113,113,114,115,113,114,113,114,115,115,117,119,124,
136,145,164,190,217,252,363,482,491,417,285,188,156,140,132,
127,122,117,118,117,115,116,115,116,118,116,116,117,116,117,
116,113,117,114,113,115,112,116,114,114,116,114,114,116,113,
116,115,114,115,115,114,115,115,115,116,114,115,116,114,118,
114,116,116,115,118,114,113,117,113,116,116,115,116,115,115,
115,114,117,116,117,118,120,118,122,119,128,127,130,134,136,
138,140,137,139,134,136,134,132,133,134,131,132,130,130,131,
128,128,131,129,131,131,134,136,134,140,139,137,143,140,138,
141,136,134,132,127,126,126,123,123,118,119,122,118,120,117,
116,118,116,118,116,115,117,116,115,116,115,115,116,114,119,
113,114,116,115,116,114,114,116,116,113,117,116,114,118,112,
115,114,113,116,115,114,115,113,116,114,114,116,115,115,114,
112,114,114,113,114,115,113,117,114,115,112,114,114,113,115,
114,114,115,113,112,115,112,113,115,112,116,113,113,115,116,
113,116,113,115,113,114,115,115,114,116,114,116,113,116,117,
113,115,116,115,117,115,114,117,113,115,118,114,116,115,115,
116,114,113,116,114,117,115,114,117,115,114,115,116,116,116,
117,117,114,0],
color: '#36D39F'
}, {
name: 'Current measured spectrum',
data: numbers,
color: '#4A235A'
}]
});
});
EDIT: here's a demo showing how mine currently functions: https://jsfiddle.net/bgzgc1d9/2/. The x-axis should range from 340 to 850 with 288 data points evenly spaced on this interval
I am trying to plot a categorical multi axis column chart of rankings. The number 1 ranking should be the tallest column and lowest ranking the shortest.
Essentially I would like the height of the bar to be it's reciprocal.
It is very close to:
var player_name_array = ["Aaron Rodgers", "Andrew Luck", "Drew Brees", "Russell Wilson", "Peyton Manning", "Ryan Tannehill", "Tony Romo", "Matt Ryan", "Cam Newton", "Ben Roethlisberger", "Eli Manning", "Philip Rivers", "Colin Kaepernick", "Teddy Bridgewater", "Marcus Mariota", "Matthew Stafford", "Robert Griffin III", "Joe Flacco", "Jay Cutler", "Sam Bradford"];
var series_array = [{"name":"espn_ranking","data":[38,33,63,64,67,95,75,85,96,76,999,999,999,999,999,999,999,999,999,999]}];
rankings_chart = new Highcharts.Chart({
chart: {
renderTo:'rankings_chart',
type: 'column'
},
title: {
text: 'Draft Rankings'
},
subtitle: {
text: 'Source: The Internet'
},
xAxis: {
categories: player_name_array,
crosshair: true
},
yAxis: {
type: 'logarithmic',
//reversed: true,
title: {
text: 'Draft Rankings'
}
},
tooltip: {
headerFormat: '<span style="font-size:14px"><b>{point.key}</b></span><table>',
pointFormat: '<tr><td style="color:{series.color};padding:0">{series.name}: </td>' +
'<td style="padding:0"><b>{point.y}</b></td></tr>',
footerFormat: '</table>',
shared: true,
useHTML: true
},
plotOptions: {
series: {
stacking:'normal',
},
column: {
pointPadding: 0.2,
borderWidth: 0
}
},
rangeSelector: {
selected: 1
},
series: series_array
});
<script src="https://code.highcharts.com/highcharts.js"></script>
<div id="rankings_chart" ></div>
The problem with this is the columns come down from the top and ranking of 1 is still the smallest column.
Is there any way to add a function for the height of each column?
Set up your data to be the inverse of the player ranking:
var rankings = [38,33,63,64,67,95,75,85,96,76,999,999,999,999,999,999,999,999,999,999]
var inv_rankings = [];
for (i = 0; i < rankings.length; i++) {
inv_rankings[i] = 1 / rankings[i]
}
Set your Highcharts data to be your inverse ranking:
series: {
name: "espn_ranking",
data: inv_rankings
}
Use a formatter for the data labels and tooltip to return the reciprocal of the reciprocal (i.e. the original value):
plotOptions: {
series: {
dataLabels: {
enabled: true,
formatter: function() {
return 1 / this.y;
}
}
},
tooltip: {
pointFormatter: function() {
return 1 / this.y;
}
}
}
Working fiddle
This was an interesting and fun puzzle to work out!
I thought the answer by nagyben was an excellent one, and I based my code on their method of inversing the scores to come up with a relative rank.
Here's a working fiddle I created based on that concept, along with several enhancements, which I've shared below: https://jsfiddle.net/brightmatrix/j4ug40qm/
I added a sort function to rank the data in descending order, no matter how the data were arranged in the original two arrays. In order to do this, I first combined both arrays into a single Javascript object.
I changed the format to a column (vertical) chart to a bar (horizontal) chart. This will make the player names more readable for your users.
I updated the tooltip to show the player's rank whenever a user hovers their cursor over a particular bar.
I removed certain chart elements that aren't needed in this kind of chart, such as the legend, gridlines, and axis labels (since you're simply doing a rank, the true value of each bar isn't relevant to the user).
Here's the sort code that I built into this:
// combine both arrays into a single object so we can then sort them by rank
var rankArray = [];
$.each(player_name_array, function(index) {
tempArray = {};
tempArray['name'] = player_name_array[index];
tempArray['y'] = 1 / series_array[index];
rankArray.push(tempArray);
});
// sort the objects by rank (the "y" value) in descending order (due to the inverse)
// see accepted answer by Stobor at:
// http://stackoverflow.com/questions/979256/sorting-an-array-of-javascript-objects
rankArray.sort(function(a, b) {
return parseFloat(b.y) - parseFloat(a.y);
});
And here's the updated chart options:
rankings_chart = new Highcharts.Chart({
chart: {
renderTo:'rankings_chart',
type: 'bar' // chose a bar vs. column chart so the player names are easier to read
},
title: { text: 'Draft Rankings' },
subtitle: { text: 'Source: The Internet' },
legend: { enabled: false }, // there is no legend needed for this chart
xAxis: {
type: 'category',
tickmarkPlacement: 'on' // place the lines directly on the player's name
},
yAxis: {
// we're measuring by rank, so there's no need for labels, gridlines, or a title
labels: { enabled: false },
title: { enabled: false },
gridLineWidth: 0
},
tooltip: {
pointFormatter: function() {
// show the rank of the player, based on their sort order
return 'ranked #' + parseInt(this.x+1);
}
},
plotOptions: {
bar: {
groupPadding: 0.1,
pointPadding: 0.2,
borderWidth: 0
}
},
series : [{
name : 'Draft Data',
data : rankArray // our array will look like this: [{name: 'NAME', y: 0}, ...]
}]
});
Here's the result:
I hope this has been helpful to you in your chart conversion.
Since you seem to already have set an upper limit of 999 for your data, i would suggest simply plotting 1000-x.
One way to do that is to let highcharts do the math in a function for the series:
series : [{
name : 'Draft Data',
data : (function () {
// generate an array of random data
var data = [];
for (var x = 0;x <= series_array.length; x += 1) {
data.push([
1000-series_array[x];
]);
}
return data;
}())
}]
JSFiddle: http://jsfiddle.net/hmjnz/4/
In this case i would hide the yaxis label and instead put annotations on the columns with the rank.
Alternatively i'd debate whether a column chart is an adequate representation for this type of data.
I'm attempting to combine a couple of different chart demos from Highcharts.
My examples are: Data classes and popup and Small US with data labels
I want the map from the first with the popup feature of the second. I need to connect the map to my own google spreadsheet but for now I'm just trying to get the data from the first example to work.
This is what I have so far but can't seem to get any data in the map. I thought I had a joinBy problem, and I may still, but when I set joinBy to null I thought "the map items are joined by their position in the array", yet nothing happened.
https://jsfiddle.net/9eq6mydv/
$(function () {
// Load the data from a Google Spreadsheet
// https://docs.google.com/a/highsoft.com/spreadsheet/pub?hl=en_GB&hl=en_GB&key=0AoIaUO7wH1HwdFJHaFI4eUJDYlVna3k5TlpuXzZubHc&output=html
Highcharts.data({
googleSpreadsheetKey: '0AoIaUO7wH1HwdDFXSlpjN2J4aGg5MkVHWVhsYmtyVWc',
googleSpreadsheetWorksheet: 1,
// custom handler for columns
parsed: function (columns) {
// Make the columns easier to read
var keys = columns[0],
names = columns[1],
percent = columns[10],
// Initiate the chart
options = {
chart : {
renderTo: 'container',
type: 'map',
borderWidth : 1
},
title : {
text : 'US presidential election 2008 result'
},
subtitle: {
text: 'Source: <a href="http://en.wikipedia.org/wiki/United_States_presidential_election,' +
'_2008#Election_results">Wikipedia</a>'
},
mapNavigation: {
enabled: true,
enableButtons: false
},
legend: {
align: 'right',
verticalAlign: 'top',
x: -100,
y: 70,
floating: true,
layout: 'vertical',
valueDecimals: 0,
backgroundColor: (Highcharts.theme && Highcharts.theme.legendBackgroundColor) || 'rgba(255, 255, 255, 0.85)'
},
colorAxis: {
dataClasses: [{
from: -100,
to: 0,
color: '#C40401',
name: 'McCain'
}, {
from: 0,
to: 100,
color: '#0200D0',
name: 'Obama'
}]
},
series : [{
data : data,
dataLabels: {
enabled: true,
color: '#FFFFFF',
format: '{point.code}',
style: {
textTransform: 'uppercase'
}
},
mapData: Highcharts.geojson(Highcharts.maps['countries/us/custom/us-small']),
joinBy: keys,
name: 'Democrats margin',
point: {
events: {
click: pointClick
}
},
tooltip: {
ySuffix: ' %'
},
cursor: 'pointer'
}, {
type: 'mapline',
data: Highcharts.geojson(Highcharts.maps['countries/us/custom/us-small'], 'mapline'),
color: 'silver'
}]
};
/**
* Event handler for clicking points. Use jQuery UI to pop up
* a pie chart showing the details for each state.
*/
function pointClick() {
var row = this.options.row,
$div = $('<div></div>')
.dialog({
title: this.name,
width: 400,
height: 300
});
window.chart = new Highcharts.Chart({
chart: {
renderTo: $div[0],
type: 'pie',
width: 370,
height: 240
},
title: {
text: null
},
series: [{
name: 'Votes',
data: [{
name: 'Obama',
color: '#0200D0',
y: parseInt(columns[3][row], 10)
}, {
name: 'McCain',
color: '#C40401',
y: parseInt(columns[4][row], 10)
}],
dataLabels: {
format: '<b>{point.name}</b> {point.percentage:.1f}%'
}
}]
});
}
// Read the columns into the data array
var data = [];
$.each(keys, function (i, key) {
data.push({
key: key,//.toUpperCase(),
value: parseFloat(percent[i]),
name: names,
row: i
});
});
// Initiate the chart
window.chart = new Highcharts.Map(options);
},
error: function () {
$('#container').html('<div class="loading">' +
'<i class="icon-frown icon-large"></i> ' +
'Error loading data from Google Spreadsheets' +
'</div>');
}
});
});
UPDATE:
I wanted to share with everyone my final solution. Although Ondkloss did a magnificent job answering my question the popup feature still didn't work and this is because I forgot to include the jQuery for the .dialog call. Once I included that I had an empty popup with a highchart error 17, this is because the highmaps.js code doesn't include the pie chart class. So I had to add the highcharts.js code and include map.js module afterward. You can see my final jsfiddle here.
Thanks again to Ondkloss for the excellent answer!
The problem here mostly comes down to the use of joinBy. Also to correct it there are some required changes to your data and mapData.
Currently your joinBy is an array of strings, like ["al", "ak", ...]. This is quite simply not an accepted format of the joinBy option. You can read up on the details in the API documentation, but the simplest approach is to have a attribute in common in data and mapData and then supply a string in joinBy which then joins those two arrays by that attribute. For example:
series : [{
data : data,
mapData: mapData,
joinBy: "hc-key",
]
Here the "hc-key" attribute must exist in both data and mapData.
Here's how I'd create the data variable in your code:
var data = [];
$.each(keys, function (i, key) {
if(i != 0)
data.push({
"hc-key": "us-"+key,
code: key.toUpperCase(),
value: parseFloat(percent[i]),
name: names[i],
row: i
});
});
This skips the first key, which is just "Key" (the title of the column). Here we make the "hc-key" fit the format of the "hc-key" in our map data. An example would be "us-al". The rest is just metadata that will be joined in. Note that you were referencing your data in the options prior to filling it with data, so this has to be moved prior to this.
This is how I'd create the mapData variable in your code:
var mapData = Highcharts.geojson(Highcharts.maps['countries/us/custom/us-small']);
// Process mapdata
$.each(mapData, function () {
var path = this.path,
copy = { path: path };
// This point has a square legend to the right
if (path[1] === 9727) {
// Identify the box
Highcharts.seriesTypes.map.prototype.getBox.call(0, [copy]);
// Place the center of the data label in the center of the point legend box
this.middleX = ((path[1] + path[4]) / 2 - copy._minX) / (copy._maxX - copy._minX);
this.middleY = ((path[2] + path[7]) / 2 - copy._minY) / (copy._maxY - copy._minY);
}
// Tag it for joining
this.ucName = this.name.toUpperCase();
});
The first part is your "standard map data". The rest is to correctly center the labels for the popout states, and gotten directly from the example.
And voila, see this JSFiddle demonstration to witness your map in action.
I suggest doing some console.log-ing to see how data and mapData have the hc-key in common and that leads to the joining of the data in the series.