HighMap data table not loading points - highcharts

I'm trying to populate a map of the U.S. in HighMaps with data from an html table. The map is showing but the data point is not. It's a latitude/longitude point. The documentation is sparse, so I'm not sure what I'm doing wrong. Here's a JSFiddle: https://jsfiddle.net/sfjeld/1wjm04fc/6/
Highcharts.mapChart('container', {
chart: {
map: 'countries/us/custom/us-all-territories'
},
series: [{
name: 'Basemap',
dataLabels: {
enabled: true,
format: '{point.name}'
}
},
{
// Specify points using lat/lon
type: 'mappoint',
data: {
table: 'pvsoiling-table',
startRow: 1,
startColumn: 1,
endColumn: 2
},
name: 'PV',
marker: {
fillColor: 'white',
lineColor: 'black',
lineWidth: 2,
radius: 10
},
color: Highcharts.getOptions().colors[1]
}
]
});
thanks,
Shauna

You can make the following changes to your code:
At the start of your <script> section, load your HTML table data into a JavaScript array:
var mapData = [];
Highcharts.data({
table: document.getElementById('pvsoiling-table'),
startColumn: 1,
endColumn: 2,
firstRowAsNames: true,
complete: function (options) {
options.series[0].data.forEach(function (p) {
mapData.push({
lat: p[0],
lon: p[1]
});
});
//console.log(mapData);
}
});
We will refer to this mapData array later on. Here is what it contains:
[
{ "lat": 33.3, "lon": -111.67 }
]
Make changes to the series section in your Highcharts.mapChart.
series: [{
name: 'Basemap',
nullColor: '#e0f9e3',
dataLabels: {
enabled: true,
format: '{point.name}'
}},
{
// Specify points using lat/lon
data: mapData,
type: 'mappoint',
name: 'PV',
marker: {
fillColor: 'white',
lineColor: 'black',
lineWidth: 1,
radius: 3
},
color: Highcharts.getOptions().colors[1]
}
]
The key part to note is the data: mapData option. The JavaScript mapData variable is the exact array that we need to represent a set of points on the map. In our case the array only contains one point - but that's because there is only one relevant row of data in the HTML table.
My map ends up looking like this:
It looks like the marker is in or near Phoenix, AZ.
Final notes:
(a) I also adjusted the marker to have lineWidth: 1 and radius: 3 (a bit smaller).
(b) I added a document ready function around everything, to ensure the DataTable is loaded before you try to read its data.
(c) There may be a more elegant way to do this, but I followed the approach in this demo. The demo actually shows how to join 2 different sets of data - not what you need. But it does show a good approach for extracting the HTML data so it can be used in the map.
Using the the Highcharts.data({...}) approach lets you access any HTML table. But since you are using DataTables, you can choose to do the following, instead. It uses the DataTables API to access each row of data:
var mapData = [];
$('#pvsoiling-table').DataTable({
"initComplete": function(settings, json) {
var api = this.api();
api.rows().data().each(function (p) {
mapData.push({ lat: Number(p[1]), lon: Number(p[2]) });
});
// your Highcharts.mapChart() logic, in a function:
buildChart();
}
});

Related

Highmaps display correctly mappoints but not maplines

I need to use Highmaps to display on a map some information such as points, lines...
Displaying the initial map and some mappoint (with latitude/longitude coordinates) works well.
But when I add a simple mapline (linestring) between 2 points already displayed on the map, the mapline is not drawn.
Here is an example : https://jsfiddle.net/vegaelce/4L928trp/
The 2 mappoints are correctly placed on the map with the following data :
data: [{
name: 'Paris',
geometry: {
type: 'Point',
coordinates: [2.34,48.86]
}
}, {
name: 'Orly',
geometry: {
type: 'Point',
coordinates: [2.40,48.75]
}
}]
But the mapline (named "road") added to link the 2 points is not displayed with the following data :
data: [{
geometry: {
type: 'LineString',
coordinates: [
[2.34,48.86], // Paris
[2.40,48.75] // Orly
]
}
}],
Do I need to add something else ?
If you use the TopoJSON maps, what you are trying to do works. https://jsfiddle.net/blaird/y1Ld6bgs/1/
(async () => {
const topology = await fetch(
'https://code.highcharts.com/mapdata/countries/fr/fr-idf-all.topo.json'
).then(response => response.json());
// Prepare demo data. The data is joined to map using value of 'hc-key'
// property by default. See API docs for 'joinBy' for more info on linking
// data and map.
var data = [
["fr-idf-se", 69699],
["fr-idf-hd", 14200],
["fr-idf-ss", 17301],
["fr-idf-vo", 14350],
["fr-idf-vm", 29728],
["fr-idf-vp", 28610],
["fr-idf-yv", 21667],
["fr-idf-es", 16494]
];
// Create the chart
Highcharts.mapChart('container', {
chart: {
map: topology
},
title: {
text: 'Highcharts Maps basic demo'
},
subtitle: {
text: 'Source map: Île-de-France'
},
series: [{
mapData: Highcharts.maps["countries/fr/fr-idf-all"],
data: data,
name: "States",
borderColor: "#ffffff",
joinBy: ["hc-key", "CODE_REGION"],
keys: ["CODE_REGION", "value"]
}, {
type: 'mapline',
data: [{
geometry: {
type: 'LineString',
coordinates: [
[2.34, 48.86], // Paris
[2.40, 48.75] // Orly
]
}
}],
showInLegend: true,
lineWidth: 2,
name: "Road",
nullColor: '#f00',
color: '#f00',
enableMouseTracking: false
}, {
type: 'mappoint',
color: '#333',
name: "Towns",
showInLegend: true,
data: [{
name: 'Paris',
geometry: {
type: 'Point',
coordinates: [2.34, 48.86]
}
}, {
name: 'Orly',
geometry: {
type: 'Point',
coordinates: [2.40, 48.75]
}
}],
enableMouseTracking: false
}]
});
})();
In the Adding Points and Lines doc: https://www.highcharts.com/docs/maps/adding-points-and-lines
Prior to v10, the coordinate system used in most of our maps was a
custom one, where both the X and Y values ranged from 0 to some
thousands. This still applies when loading GeoJSON maps rather than
TopoJSON maps from the Map Collection. With the support of the proj4js
library, points could be placed by the lon and lat options. Without
proj4.js, points were added as x, y pairs on the same coordinate
system as the map. Maplines however were given as paths.
It explains that if you don't use the Topo data, you'll have to either convert the coordinates, or use the same coordinate system as the map for lines.
P.S. Not sure why setting color of the line doesn't work, but setting nullColor does. But, that is what I had to do to make the line red
After digging into I think that it is a bug and I reported it on the Highcharts Github issue channel where you can follow this thread: https://github.com/highcharts/highcharts/issues/17086

How to show two specific data points from tabular data in Highcharts?

I am trying to plot a chart with only two data points from a CSV file that holds many more data points with a datetime x-Axis.
In the end the user should be able to compare two years of his choice out of the whole dataset.
From the API documentation I know that I can pick a range of data points from a CSV with startRow and endRow:
https://api.highcharts.com/highcharts/data.startRow
But that would only plot one specific point, as you can see in my fiddle.
Is there any other way to programmatically show specific points?
Highcharts.chart('container', {
chart: {
type: 'column',
polar: false,
},
title: {
text: ''
},
subtitle: {
text: ''
},
data: {
csv: document.getElementById('csv').innerHTML,
startRow: 3,
endRow: 4,
googleSpreadsheetKey: false,
googleSpreadsheetWorksheet: false
},
series: [{
name: 'val'
}],
yAxis: [{
title: {
text: ''
},
opposite: true,
labels: {
align: 'right',
reserveSpace: true
}
}],
xAxis: [{
type: 'datetime',
opposite: false
}],
pane: {
background: []
},
responsive: {
rules: []
},
legend: {
title: ''
},
plotOptions: {
series: {
animation: false
}
}
});
Edit:
I forgot to mention, that i only want to load the CSV once. After that the user should be able to select/update data points without reloading the data.
For showing ranges of values dynamically, I used Axis min and max settings like this:
$(this).highcharts().update({
xAxis:{
min: Date.UTC(selectedStart,0,0),
max: Date.UTC(selectedEnd,11,31)
}
});
The whole dataset is loaded once and the chart axis gets updated on user interaction.
Now I am looking for something similar just not for a range but a comparison of two values off of the whole dataset.
Highcharts data module provides a function called parsed that allows you to modify the fetched data programmatically before it's applied to the chart.
From Highcharts API (https://api.highcharts.com/highcharts/data.parsed):
parsed: function
A callback function to access the parsed columns, the
two-dimentional input data array directly, before they are
interpreted into series data and categories. Return false to stop
completion, or call this.complete() to continue async.
Live demo: http://jsfiddle.net/gh/get/library/pure/highcharts/highcharts/tree/master/samples/highcharts/data/parsed/

Highcharts : selection

I made a barchart with dates. Currently, to remove the dates, you must click on the dates in the legend. I wish delete multiple dates at once.
Let's take an example. My dates range from 1960 to 2015. If I would have on my chart the dates from 2000 to 2005, so I would like that if you click on 1960 and 1999, then all the dates between are deleted / hidden. It goes faster when many dates.
How to do ?
Here is my code :
$(function () {
$('#container').highcharts({
chart: {
type: 'column'
},
colors:[
'#7cb5ec',
'#434348',
'#90ed7d',
'#f7a35c',
'#8085e9',
'#f15c80',
'#e4d354',
'#2b908f',
'#f45b5b',
'#91e8e1',
'#DA70D6',
'#1E90FF',
'#E0F000'
],
legend:{
itemStyle:{
fontSize:'10px',
font:'10pt',
color:'#000000'
}
},
title:{
style:{
fontSize:'0px'
}
},
subtitle:{
style:{
fontSize:'0px'
}
},
xAxis: {
categories: [
'',
],
},
yAxis: {
min: 15,
title: {
text: 'Number',
style:{
fontSize:'0px'
}
}
},
tooltip: {
shared: false,
useHTML: true
},
plotOptions: {
column: {
pointPadding: 0.2,
borderWidth: 0
}
},
series: [{
name: '2004',
data: [49.9],
},
{
name: '2005',
data: [83.6]
},
{
name: '2006',
data: [48.9]
},
{
name: '2007',
data: [69.1]
},
{
name: '2008',
data: [83.6]
},
{
name: '2009',
data: [40.9]
},
{
name: '2010',
data: [69.9]
},
{
name: '2011',
data: [83]
},
{
name: '2012',
data: [28.9]
},
{
name: '2013',
data: [40.9]
},
{
name: '2014',
data: [81.6]
},
{
name: '2015',
data: [24.9]
},
{
name: '2016',
data: [46.4]
}]
});
});
Thanks
Rather than having each year as its own series, I would recommend that you place the years as the values in your x-axis (as categories) and then use Highcharts' native zoom function to allow users to select a certain date range.
I've updated your fiddle with some changes, which I explain below: https://jsfiddle.net/brightmatrix/hr28s27L/
First, in your chart option, I added zoomType: 'x' to allow users to use their mouse to zoom in on specific years. The value x means they can only zoom horizontally (across), which makes for a "cleaner" interaction.
chart: {
type: 'column',
zoomType: 'x'
},
Second, I updated your x-axis with the years as the categories/values:
xAxis: {
categories: ['2004','2005','2006','2007','2008','2009','2010','2011','2012','2013','2014','2015','2016']
},
Lastly, I updated your series to show just the data points, which are then plotted on the y-axis:
series: [{
name: 'data by year',
data: [49.9,83.6,48.9,69.1,83.6,40.9,69.9,83,28.9,40.9,81.6,24.9,46.4]
}]
Here is what happens when a user clicks and drags their mouse cursor:
The shaded box is what they are selecting. Once they release the cursor, the chart will automatically adjust to show only what they chose. A "Reset Zoom" button will appear at the top right to allow them to go back to all years:
Update (July 19, 2016): I did some research on adding a simple slider element to this chart that allows users to choose from a range of years.
An updated version of my fiddle that shows this example chart with sliders can be found here: https://jsfiddle.net/brightmatrix/uvat8u05/.
The code to handle the sliders is shown below. I discovered that explicitly setting the slider values to integers using the parseInt() function solved a couple of problems:
You can correctly compare the slider values to make sure users can't choose an end year that is earlier than the start year.
The setExtremes() function correctly shows a single year when users choose the same start and end year.
All x-axis labels are shown at all times. Before I added parseInt(), some labels disappeared when users chose different values in the sliders.
Please be sure to read the comments I've left in both the HTML and Javascript panes, as I've included additional details on why I made certain code decisions.
// on change handler for both sliders
$('.mySlider').bind('change', function(e) {
e.preventDefault();
var chart = $('#container').highcharts();
// convert the slider values to integers to make sure setExtremes() works as expected
var slider1Val = parseInt($('input[name="slider1"]').val());
var slider2Val = parseInt($('input[name="slider2"]').val());
if (slider2Val < slider1Val) {
// warn the user if they try to choose an end year that is later than the start year
alert("You can't choose an end year that is earlier than your start year.");
} else {
// use setExtremes to set the x-axis ranges based on the values in the sliders
chart.xAxis[0].setExtremes(slider1Val, slider2Val);
}
});
I hope this information is helpful for you.

How to change highmap bubble color

I am trying to color the bubbles based on the name of the cities. Something like if this.point.capital == Montgomery & this.point.capital == Juneau; color = "red". But I cannot add this if function to the color attribute. Can you help me out?
Thanks!!!!
series: [{
name: 'Basemap',
mapData: map,
borderColor: '#606060',
nullColor: 'rgba(200, 200, 200, 0.2)',
showInLegend: false
}, {
name: 'Separators',
type: 'mapline',
data: H.geojson(map, 'mapline'),
color: '#101010',
enableMouseTracking: false
}, {
type: 'mapbubble',
dataLabels: {
enabled: true,
format: '{point.capital}'
},
name: 'Cities',
data: data,
maxSize: '12%',
color: H.getOptions().colors[0]
}]
http://jsfiddle.net/oufwhmz0/
Do this for each bubble individually (not the series as a whole) in the data array prior to initiating the chart. For example extending your code (JSFiddle):
function determineColor(entry) {
if(entry.capital == "Montgomery")
return "#FF00FF";
else if(entry.capital == "Salt Lake City")
return "#00FF00";
return null;
}
// Add series with state capital bubbles
$.getJSON('http://www.highcharts.com/samples/data/jsonp.php?filename=us-capitals.json&callback=?', function (json) {
var data = [];
$.each(json, function (ix, entry) {
entry.z = entry.population;
entry.color = determineColor(entry); // Added
data.push(entry);
});
// ... rest as usual
});
This just sets the color for each entry (which will be a bubble), as defined by the determineColor function.

Highstock Issue - Can't draw and plot chart correctly

I'm working on project to display stock information using Highstock.
Question 1:
I tried to display ohlc data using ohlc graph, high and low using areasplinerange graph, and volume using column chart.
Everything works fine, if i zoom 1m, 3m, 6m, YTD, and 1y. Here is the snapshot. link1. But if zoom to All, The graph messed up like this link2.
Am i wrong in my coding or it's bug?
Question 2:
In the same chart, I have code to change the type of graph from ohlc to line. It works fine when I zoom to 1m, 3m. Here is the snapshot link3. But it show me no line chart when i zoom to 6m, 1y, and All. Here is the snapshot link4.
How can this happen?
Thank you for your help.
The Code:
Here is the code that i used to display the chart
$.getJSON(url, function (data1) {
$.getJSON(urlprediction, function (data2) {
var ohlc = [],
volume = [],
closed = [],
forecast = [],
dataLength1 = data1.length;
dataLength2 = data2.length;
for (i = 0; i < dataLength1; i++) {
ohlc.push([
data1[i][0], // the date
data1[i][1], // open
data1[i][2], // high
data1[i][3], // low
data1[i][4] // close
]);
closed.push([
data1[i][0], // the date
data1[i][4] // close
]);
volume.push([
data1[i][0], // the date
data1[i][5] // the volume
])
}
for (i = 0; i < dataLength2; i++) {
forecast.push([
data1[i][0], // the date
data1[i][1],
data1[i][2], // close
])
}
// set the allowed units for data grouping
var groupingUnits = [[
'week', // unit name
[1] // allowed multiples
], [
'month',
[1, 2, 3, 4, 6]
]];
$('#container').highcharts('StockChart', {
rangeSelector: {
selected: 1
},
title: {
text: title
},
yAxis: [{
title: {
text: 'OHLC'
},
height: 360,
lineWidth: 2
}, {
title: {
text: 'Volume'
},
top: 433,
height: 100,
offset: 0,
lineWidth: 2
}],
series: [{
type: 'ohlc',
name: stockname,
data: ohlc,
}, {
type: 'areasplinerange',
name: stockname,
data: data2,
}, {
type: 'column',
name: 'Volume',
data: volume,
yAxis: 1,
}]
});
});
});

Resources