Extending Highchart's show() and hide() functions - javascript

What would be the best approach to extend the show() and hide() functions in Highcharts?
I want to add a boolean-like show(effectLinkedSeries) and hide(effectLinkedSeries), so I can control when a linkedSeries gets removed or added along with its "parent". Here is a demo of linkedSeries functionality. A property called "linkedTo" sets up the functionality:
series: [{
name: 'Temperature',
data: averages,
zIndex: 1,
marker: {
fillColor: 'white',
lineWidth: 2,
lineColor: Highcharts.getOptions().colors[0]
}
}, {
name: 'Range',
data: ranges,
type: 'arearange',
lineWidth: 0,
linkedTo: ':previous',
color: Highcharts.getOptions().colors[0],
fillOpacity: 0.3,
zIndex: 0
}]
I could modify the source directly but I'd rather try to extend the library, instead of hacking it.

Figured out I can make use of the Highcharts.Series.prototype to accomplish this
Highcharts.Series.prototype.setVisible = function (vis, redraw, effectLinkedSeries) {
var series = this,
chart = series.chart,
legendItem = series.legendItem,
showOrHide,
ignoreHiddenSeries = chart.options.chart.ignoreHiddenSeries,
oldVisibility = series.visible;
// if called without an argument, toggle visibility
series.visible = vis = series.userOptions.visible = vis === Highcharts.UNDEFINED ? !oldVisibility : vis;
showOrHide = vis ? 'show' : 'hide';
// show or hide elements
Highcharts.each(['group', 'dataLabelsGroup', 'markerGroup', 'tracker'], function (key) {
if (series[key]) {
series[key][showOrHide]();
}
});
// hide tooltip (#1361)
if (chart.hoverSeries === series || (chart.hoverPoint && chart.hoverPoint.series) === series) {
series.onMouseOut();
}
if (legendItem) {
chart.legend.colorizeItem(series, vis);
}
// rescale or adapt to resized chart
series.isDirty = true;
// in a stack, all other series are affected
if (series.options.stacking) {
Highcharts.each(chart.series, function (otherSeries) {
if (otherSeries.options.stacking && otherSeries.visible) {
otherSeries.isDirty = true;
}
});
}
// show or hide linked series
Highcharts.each(series.linkedSeries, function (otherSeries) {
if (effectLinkedSeries === true) {
otherSeries.setVisible(vis, false);
}
});
if (ignoreHiddenSeries) {
chart.isDirtyBox = true;
}
if (redraw !== false) {
chart.redraw();
}
Highcharts.fireEvent(series, showOrHide);
}; // end Highcharts.Series.prototype.setVisible
Highcharts.Series.prototype.show = function (effectLinkedSeries) {
this.setVisible(true,undefined,effectLinkedSeries);
};
Highcharts.Series.prototype.hide = function (effectLinkedSeries) {
this.setVisible(false,undefined,effectLinkedSeries);
};

Related

Javascript force insert string into JS object (JSON) leaflet vectortiles

I am using leaflet mapping library
for styling purposes this code works for the data_oh.parcel layer if I hardcode the layer name like this
var vectorTileOptions = {
interactive: true,
vectorTileLayerStyles: {
'data_oh.parcel': {
fillColor: "yellow",
fill: true,
color: "red"
}
}
};
However as I am going to be adding multiple layers I need to add that layer name as a variable so I have something like this
var layers={parcels: ["#Parcels","http://localhost:7800/data_oh.parcel/{z}/{x}/{y}.pbf",'#ffe4c4','data_oh.parcel'],
footpring: ["#Footprints","http://localhost:7800/data_oh.footprint/{z}/{x}/{y}.pbf",'#8b8878','data_oh.footprint']
};
var idArray = [];
var layerArray = [];
function legend_click(id, layer_api, color_layer,layer_name) {
$(id).click(function () {
var layer_add;
var i = idArray.indexOf(id);
if (i < 0) {
layer_add = L.vectorGrid.protobuf(layer_api, {
interactive: true,
rendererFactory: L.svg.tile,
vectorTileLayerStyles: {
layer_name: {
fillColor: "yellow",fill: true, color: "red"
}
}
})
layerArray.push(layer_add);
idArray.push(id);
}
else {
layer_add = layerArray[i];
};
if ($(id).prop('checked') == true) {
layer_add.addTo(map);
}
else if ($(id).prop('checked') == false) {
map.removeLayer(layer_add);
}
})
};
for (var key in layers){
legend_click(layers[key][0],layers[key][1],layers[key][2],layers[key][3])
};
In the legend_click function the 4th input is for that layer name but the color is not changing on the map, this means the 4th input is not being recognized correctly in the vectorTileLayerStyles portion of the code. Again if I hardcode the values it works but passing through on a variable holding a string it does not.
You can use computed property names inside legend_click:
vectorTileLayerStyles: {
[`${layer_name}`]: {
fillColor: "yellow",fill: true, color: "red"
}
}
so if that did not work this should work:
vectorTileLayerStyles: Object.fromEntries([[layer_name,{fillColor: "yellow", fill: true, color: "red"}]])

JavaScript - iterating through an array for checking condition

I am creating a high charts graph that I would like to dynamically give the graph color to depending on the title of an object. I currently have an array graphData that has an object title.
I have 5 possible results of titles:
"LOW", "MEDIUM-LOW", "MEDIUM", "MEDIUM-HIGH", AND "HIGH"
I am now attempting to iterate through my array and assign a color depending on what title the index has.
My entire graph receives one color based off the last title of the array. I would like the color to effect each index of the array seperartely.
For example: if "MEDIUM-HIGH" is the last title in the array, my entire graph gets #DD5F0C
Here is my code:
Array:
graphData: [ […]
​
0: Object { title: "LOW", result: 62582 }
​
1: Object { title: "MEDIUM-LOW", result: 57758 }
​
2: Object { title: "LOW", result: 8795 }
​
3: Object { title: "HIGH", result: 262525 }
​
4: Object { title: "MEDIUM-HIGH", result: 167168 } ]
let graphColor = ""
for (i = 0; i < graphData.length; i++) {
if (graphData[i].title === "LOW") {
graphColor = "#0D6302"
} else if (graphData[i].title === "MEDIUM-LOW") {
graphColor = "#0B7070"
} else if (graphData[i].title === "MEDIUM") {
graphColor = "#DC9603"
} else if (graphData[i].title === "MEDIUM-HIGH") {
graphColor = "#DD5F0C"
} else if (graphData[i].title === "HIGH") {
graphColor = "#C50710"
}
}
HighCharts code :
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: `graphData[0].title`,
color: graphColor,
data: [graphData[0]],
}, {
name: 'graphData[1].title',
color: graphColor,
data: [graphData[1]],
showInLegend: false,
linkedTo: ":previous"
}, {
name: 'graphData[2].title,
color: graphData[0].title,
data: [graphData[2]]
}, {
name: graphData[3].title,
color: '#DC9603',
data: [graphData[3]]
}, {
name: graphData[4].title,
color: graphColor,
data: [graphData[4]]
}, {
name: graphData[5].title,
color: graphColor,
data: [graphData[5]]
}]
});
I am expecting my "color" to be dynamically generated based off of what graphData.title equals for that specific index.
You are having trouble because you have graphData.length number of entries, but only one graphColor variable to hold the color. Your code samples don't look complete so I'll make some assumptions about how the surrounding code must be. I recommend building up your series data in the for-loop directly so you can just use it in the Highcharts.chart call. The code is easier to read that way and probably more flexible too if you need to have more data rows.
// build the series data array here so it's simple to use in the chart call
const series = new Array(graphData.length);
for (let i = 0; i < graphData.length; i++) {
let graphColor = "#000000"; // a default color just in case
// can use if/else or a switch here
if (graphData[i].title === "LOW") {
graphColor = "#0D6302";
} else if (graphData[i].title === "MEDIUM-LOW") {
graphColor = "#0B7070";
} else if (graphData[i].title === "MEDIUM") {
graphColor = "#DC9603";
} else if (graphData[i].title === "MEDIUM-HIGH") {
graphColor = "#DD5F0C";
} else if (graphData[i].title === "HIGH") {
graphColor = "#C50710";
}
series[i] = {
name: graphData[i].title,
color: graphColor,
data: [graphData[i].result]
};
}
// Adjust the series data as needed
series[1].showInLegend = false;
series[1].linkedTo = ":previous";
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: series
});
Not sure if I've properly understood what are you trying to do, but try this way:
const colorMap = { "LOW":"#0D6302",
"MEDIUM-LOW": "#0B7070",
"MEDIUM": "#DC9603",
"MEDIUM-HIGH": "#DD5F0C",
"HIGH":"#C50710"
}
...
series: [{
name: `graphData[0].title`,
color: colorMap[graphData[0].title],
data: [graphData[0]],
}, {
In the Highchart way - you can iterate through the series after chart initialization and set the wanted colors by particular series.
Demo: https://jsfiddle.net/BlackLabel/6hm4ebna/
chart: {
type: 'bar',
events: {
load() {
let chart = this;
chart.series.forEach(s => {
console.log(s)
if (s.name === 'test1') {
s.update({
color: 'red'
})
}
else if (s.name === 'test3') {
s.update({
color: 'green'
})
}
})
}
}
},
API: https://api.highcharts.com/highcharts/chart.events.load
If this wouldn't help please reproduce your attempt with the sample data on the online editor which I could work on.

I build synchronized charts (highcharts) that I want to export in one PDF

Ok so I build sync charts with test data. Everything works perfectly. The only problem I have is that I want to export all of them in one PDF but I only have the option to do it seperatly. So I build in a button that gets the charts in an array and exports it to PDF but it does not want to work.
This is the JS i have that builds the charts
function clickModal(test) {
document.getElementById("myModal").style.display = "block";
// Call the AJAX function that start the chart procedures
getAjaxData(test);
}
// HIGHCHART FUNCTIONALITY STARTS HERE
['mousemove', 'touchmove', 'touchstart'].forEach(function (eventType) {
document.getElementById('container').addEventListener(
eventType,
function (e) {
var chart,
point,
i,
event;
for (i = 0; i < Highcharts.charts.length; i = i + 1) {
chart = Highcharts.charts[i];
// Find coordinates within the chart
event = chart.pointer.normalize(e);
// Get the hovered point
point = chart.series[0].searchPoint(event, true);
if (point) {
point.highlight(e);
}
}
}
);
});
/**
* Override the reset function, we don't need to hide the tooltips and
* crosshairs.
*/
Highcharts.Pointer.prototype.reset = function () {
return undefined;
};
/**
* Highlight a point by showing tooltip, setting hover state and draw crosshair
*/
Highcharts.Point.prototype.highlight = function (event) {
event = this.series.chart.pointer.normalize(event);
this.onMouseOver(); // Show the hover marker
this.series.chart.tooltip.refresh(this); // Show the tooltip
this.series.chart.xAxis[0].drawCrosshair(event, this); // Show the crosshair
};
/**
* Synchronize zooming through the setExtremes event handler.
*/
function syncExtremes(e) {
var thisChart = this.chart;
if (e.trigger !== 'syncExtremes') { // Prevent feedback loop
Highcharts.each(Highcharts.charts, function (chart) {
if (chart !== thisChart) {
if (chart.xAxis[0].setExtremes) { // It is null while updating
chart.xAxis[0].setExtremes(
e.min,
e.max,
undefined,
false,
{ trigger: 'syncExtremes' }
);
}
}
});
}
}
function getAjaxData(test){
$.getJSON('datasync.php', function(chartData, tstSuccess) {
// Display the results of the getJSON call to data.php
document.getElementById("json1").innerHTML = JSON.stringify(tstSuccess, undefined, 2);
document.getElementById("json").innerHTML = JSON.stringify(chartData, undefined, 2);
var charts1 = {}; // global variable
var index = 0;
// Loop through each dataset in the returned JSON
chartData.datasets.forEach(function (dataset, i) {
// Add X values
dataset.data = Highcharts.map(dataset.data, function (val, j) {
return [chartData.xData[j], val];
});
// Create a child div for each dataset that is returned
var chartDiv = document.createElement('div');
chartDiv.className = 'chart';
document.getElementById('container').appendChild(chartDiv);
charts1[index] = Highcharts.chart(chartDiv, {
chart: {
marginLeft: 40, // Keep all charts left aligned
spacingTop: 20,
spacingBottom: 20
},
exporting: {
buttons: {
contextButton: {
menuItems: [
'downloadPDF',
'viewData'
]
}
}
},
title: {
text: dataset.name,
align: 'left',
margin: 0,
x: 30
},
credits: {
enabled: false
},
legend: {
enabled: false
},
xAxis: {
crosshair: true,
events: {
setExtremes: syncExtremes
},
labels: {
//format: '{value} km'
format: ' '
}
},
yAxis: {
title: {
text: null
}
},
tooltip: {
positioner: function () {
return {
// right aligned
x: this.chart.chartWidth - this.label.width - 40,
y: 10 // align to title
};
},
borderWidth: 0,
backgroundColor: 'none',
pointFormat: '{point.y}',
headerFormat: '',
shadow: false,
style: {
fontSize: '18px'
},
valueDecimals: dataset.valueDecimals
},
series: [{
data: dataset.data,
name: dataset.name,
type: dataset.type,
color: Highcharts.getOptions().colors[i],
fillOpacity: 0.3,
tooltip: {
valueSuffix: ' ' + dataset.unit
}
}]
});
});
index++;
});
}
$('#export-pdf').click(function() {
Highcharts.exportCharts([charts1[0], charts1[1]], {
type: 'application/pdf'
});
});
And this is my HTML
<div id="myModal" class="modal">
<div class="modal-content">
<span class="close">×</span>
<div id="container">
<button id="export-png">Export to PNG</button>
</div>
</div>
</div>
So im using PHP to build up JSON from an array ( will use SQL to build from database later just want to get the functionality working )
Then I use the highcharts library along with JS to display the charts
Ok so I figured out the problem. I brought in this piece of code
Highcharts.getSVG = function(charts) {
var svgArr = [],
top = 0,
width = 0;
$.each(charts, function(i, chart) {
var svg = chart.getSVG();
svg = svg.replace('<svg', '<g transform="translate(0,' + top + ')" ');
svg = svg.replace('</svg>', '</g>');
svg = svg.replace('-9000000000', '-999'); // Bug in v4.2.6
top += chart.chartHeight;
width = Math.max(width, chart.chartWidth);
svgArr.push(svg);
});
return '<svg height="'+ top +'" width="' + width + '" version="1.1" xmlns="http://www.w3.org/2000/svg">' + svgArr.join('') + '</svg>';
};
/**
* Create a global exportCharts method that takes an array of charts as an argument,
* and exporting options as the second argument
*/
Highcharts.exportCharts = function(charts, options) {
// Merge the options
options = Highcharts.merge(Highcharts.getOptions().exporting, options);
// Post to export server
Highcharts.post(options.url, {
filename: options.filename || 'chart',
type: options.type,
width: options.width,
svg: Highcharts.getSVG(charts)
});
};
I changed the charts so that it does not created an array of chart objects
Highcharts.chart(chartDiv, {
chart: {
marginLeft: 40, // Keep all charts left aligned
spacingTop: 20,
spacingBottom: 20
},
instead of
charts1[index] = Highcharts.chart(chartDiv, {
chart: {
marginLeft: 40, // Keep all charts left aligned
spacingTop: 20,
spacingBottom: 20
},
And in the buttons function I just used the highcharts.charts instead of the array
$('#export-pdf').click(function() {
Highcharts.exportCharts(Highcharts.charts, {
type: 'application/pdf'
});
});

Flot animating a vertical line from one point to other

I am stuck in a bit of a problem. You people might have seen an animated line which acts like a scanner in many apps. Well I ned something similar to that but I need it in a graph.
What I actually need is that I need to plt a vertical line which moves from one point to other automatically.
Let me give you a bit more explaination:
1. I have a button
2. I press the button and graph area appears.
3. On the graph area, a vertical line scrolls through the area as if it is scanning the area.
I am able to plot the line but it is coming out to be a little tilted. The logic behind that is provided below:
for(i=0;i<frequencyArray.length;i++){
myTestArray2.push([i,outFrequencyArray[i]]);
}
plot.setData([
{data:myTestArray2,lines:{fill:false,lineWidth:3},shadowSize:10}
]);
function setUpflot(){
// setup plot
//console.log("setUpflot");
var options = {
// series : { shadowSize: 0, splines: {show:true,lineWidth:1}},
series : { },
yaxis : { ticks: 5, tickColor:"rgba(148,129,151,0.5)", min: minGraphY, max:maxGraphY,show: true},
xaxis : { tickLength:0, show: false },
grid : { borderWidth:0,markings:[
{yaxis: { from: 200.0, to: 240.0 },color: "rgba(140,2,28,0.5)"}
]}
};
I put this together in response to a comment yesterday.
Fiddle here.
Produces:
plot = $.plot($("#placeholder"),
[ { data: someData} ], {
series: {
lines: { show: true }
},
crosshair: { mode: "x" }, // turn crosshair on
grid: { hoverable: true, autoHighlight: false },
yaxis: { min: -1.2, max: 1.2 }
});
crossHairPos = plot.getAxes().xaxis.min;
direction = 1;
setCrossHair = function(){
if (direction == 1){
crossHairPos += 0.5;
}
else
{
crossHairPos -= 0.5;
}
if (crossHairPos < plot.getAxes().xaxis.min){
direction = 1;
crossHairPos = plot.getAxes().xaxis.min;
}
else if (crossHairPos > plot.getAxes().xaxis.max)
{
direction = 0;
crossHairPos = plot.getAxes().xaxis.max;
}
plot.setCrosshair({x: crossHairPos})
setTimeout(setCrossHair,100);
}
// kick it off
setTimeout(setCrossHair,100);
var frequencyIndex = 0; //dynamic values stored intialised with 0.
var outFrequencyArray = [];
for(i=0;i<totalPoints;i++){
outFrequencyArray.push(minGraphY-1);
}
opd=Math.tan(Math.PI/2);
outFrequencyArray.splice(frequencyIndex,0,opd);
frequencyIndex++;
for(i=0;i<frequencyArray.length;i++){
myTestArray2.push([i,outFrequencyArray[i]]);
}
plot.setData([
{data:myTestArray2,lines:{fill:false,lineWidth:3},shadowSize:10}
]);
function setUpflot(){
// setup plot
//console.log("setUpflot");
var options = {
// series : { shadowSize: 0, splines: {show:true,lineWidth:1}},
series : { },
yaxis : { ticks: 5, tickColor:"rgba(148,129,151,0.5)", min: minGraphY, max:maxGraphY,show: true},
xaxis : { tickLength:0, show: false },
grid : { borderWidth:0,markings:[
{yaxis: { from: 200.0, to: 240.0 },color: "rgba(140,2,28,0.5)"}
]}
};

Highcharts - column chart redraw animation

I'm trying to update an existing data series with a new data array and invoke the redraw function when done. While this works perfectly, I'm not quite satisfied as I'd like to have a sort of grow/shrink transition. I have seen an example by Highcharts (fiddle around with the existing data set then click on the button "Set new data to selected series") but I can't replicate this behavior.
This is what code that I've written:
var series, newSeriesThreshold = this.chart.series.length * 2;
for (var i = 0; i < data.length; i += 2) {
series = {
name: this.data[i].title,
data: this.data[i].data,
color: this.data[i].color
};
if (i >= newSeriesThreshold) {
this.chart.addSeries(series, false);
} else {
var currentSeries = this.chart.series[i / 2];
currentSeries.setData(series.data, false);
}
}
this.chart.redraw();
These are the options when creating the chart:
var config = {
chart: {
renderTo: $(this.container).attr('id'),
type: this.settings.type,
animation: {
duration: 500,
easing: 'swing'
}
},
title: {
text: null
},
legend: {
enabled: this.settings.legend.show
},
tooltip: {
formatter: function() {
return this.x.toFixed(0) + ": <b>" + this.y.toString().toCurrency(0) + '</b>';
}
},
xAxis: {
title: {
text: this.settings.xaxis.title,
style: {
color: '#666'
}
}
},
yAxis: {
title: {
text: this.settings.yaxis.title,
style: {
color: '#666'
}
}
},
series: series,
plotOptions: {
column: {
color: '#FF7400'
}
},
credits: {
enabled: false
}
};
This yields an immediate update without transitioning effects. Any ideas what I might be doing wrong?
I have solved this problem by destroying and creating again the chart.
Here is the link on highcharts forum that helps me : http://forum.highcharts.com/highcharts-usage/animation-on-redraw-t8636/#p93199
The answer comes from the highcharts support team.
$(document).ready(function() {
var chartOptions = {
// Your chart options
series: [
{name: 'Serie 1' , color: '#303AFF', data: [1,1,1,1,1,1,1}
]
};
var chart = new Highcharts.Chart(chartOptions);
$("#my_button").click(function(){
chart.destroy();
chartOptions.series[0].data = [10,5,2,10,5,2,10];
chart = new Highcharts.Chart(chartOptions);
});
});
This remain a mystery. I managed to make the axis update which suggests that there is some kind of animation going on, but it's applied only to the axis, and not the columns.
In the end, I've settled with this behavior.
This might help:
var mychart = $("#mychart").highcharts();
var height = mychart.renderTo.clientHeight;
var width = mychart.renderTo.clientWidth;
mychart.setSize(width, height);
to update all charts
$(Highcharts.charts).each(function(i,chart){
var height = chart.renderTo.clientHeight;
var width = chart.renderTo.clientWidth;
chart.setSize(width, height);
});

Categories

Resources