Highcharts Gauge misplaced labels - javascript

I'm using highcharts solid gauge with decimal value. Here is the jsfiddle http://jsfiddle.net/7hm1mkbn/
$('#container-temp').highcharts(Highcharts.merge(gaugeOptions, {
yAxis: {
min: 10.39,
max: 23.83,
title: {
text: 'Speed'
}
},
credits: {
enabled: false
},
series: [{
name: 'Temperature',
data: [23.23],
dataLabels: {
format: '<div style="text-align:center"><span style="font-size:25px;color:' +
((Highcharts.theme && Highcharts.theme.contrastTextColor) || 'black') + '">{y}</span><br/>' +
'<span style="font-size:12px;color:silver">C</span></div>'
},
tooltip: {
valueSuffix: ' C'
}
}]
}));
The min-max labels are misplaced. Any suggestion?

If you only want min and max ticks (with labels) you can replace your tickPixelInterval with a static definition of tickPositions. For example (JSFiddle):
yAxis: {
tickPositions: [10.39, 23.83]
}
If you may want more ticks (and labels) you may want to make a more dynamic function using tickPositioner. For example (JSFiddle):
yAxis: {
tickPositioner: function () {
var positions = [],
numberOfTicks = 5;
tick = this.min,
increment = (this.max - this.min) / (numberOfTicks - 1);
for (tick; tick - increment <= this.max; tick += increment) {
positions.push(Math.round(tick * 100) / 100);
}
return positions;
}
}

Related

Highligligh particular areas based on X-axis data

SO What I am trying to do is that I am trying to fetch data from CSV File, and from other CSV file I am trying to Highlight a particular area from the Chart.
For Eg.:
This is the Chart I am getting .
By adding the Following Code.
$.get('abc.csv', function(data) {
var lines = []
lines = data.split('\n');
console.log(lines);
var ecgData=[];
$.each(lines, function(lineNo, lineContent){
if(lineNo >= 0)
{
ecgData[lineNo-0] = parseFloat(lineContent.substring(lineContent.lastIndexOf(",")+1) );
//gibber=500;
//m=m+500;
}//console.log('PPG Data', ppgData[ppgNo-0])
});
featurex = [5,10,14,34,56,78,90,95] ;
featurey = [0,0,1,0,0,3,0,2];
zip = (xs, ys) => xs.reduce((acc, x, i) => (acc.push([x, ys[i]]), acc), []);
//console.log(ecg);
console.log(ecgData);
Highcharts.chart('ecg', {
chart: {
type: 'line',
zoomType: 'xy',
panning: true,
panKey: 'shift'
},
credits: {
enabled: false
},
title: {
text: 'ECG Data'
},
subtitle: {
text: ''
},
xAxis: {
crosshair: false
},
yAxis: {
title: {
text: 'ECG Peaks'
}
},
tooltip: {
enabled: false
},
plotOptions: {
column: {
pointPadding: 0.2,
borderWidth: 0
}
},
series: [{
name: '',
lineWidth: 1,
data: ecgData,
animation: {
duration: 14000
}
},
{ type: 'column',
name: 'Features',
data: zip(featurex, featurey),
animation: {
duration: 14000
}
}
]
});
});
My Chart :
Now as you can see from the Chart. I am getting the features data as bars in the chart.
featurex = [5,10,14,34,56,78,90,95] ;
featurey = [0,0,1,0,0,3,0,2];
but that is not what I want what I want is that where the features x value is 1, I want to highlight that area with a particular color, where it is 2, it should be filled with other color Like an example below:
Note: its just an example how the data should look don't math the data with the above image data.
I hope my question is clear.
In the load event you can check if a point meets your condition and add plotBands to your chart.
chart: {
events: {
load: function() {
var xAxis = this.xAxis[0],
points = this.series[0].points,
from,
to,
plotBands = [];
points.forEach(function(point, i) {
from = points[i - 1] ? points[i - 1].x : point.x;
to = points[i + 1] ? points[i + 1].x : point.x;
if (point.y === 1) {
plotBands.push({
color: 'blue',
from: from,
to: to
});
} else if (point.y === 2) {
plotBands.push({
color: 'green',
from: from,
to: to
});
}
});
xAxis.update({
plotBands: plotBands
});
}
}
}
Live demo: http://jsfiddle.net/BlackLabel/vm0ouwp5/
API Reference: https://api.highcharts.com/highcharts/xAxis.plotBands

How can I contain a label on a Highcharts area chart to the series' area

For some reason no matter what we try the labels on our area chart series seem to have a mind of their own. Even though a short label looks like it could fit inside the area of the data, it puts it right on the end line, bleeding out of the area.
We suspect it might be due to having min and max dates that are beyond the series min and max, but these buffer zones are a requirement.
Is there an option to make labels be contained to their own series and not bleed off into whitespace?
Below is the example chart configuration and here is the JSFiddle: http://jsfiddle.net/sLqu34cn/
Highcharts.chart('container', {
chart: {
type: "area",
height: 200
},
legend: {
enabled: false
},
plotOptions: {
area: {
stacking: "percent",
pointPlacement: "on"
},
series: {
lineWidth: 0,
fillOpacity: 1,
marker: {
enabled: false
},
label: {
style: {
color: "white",
textOutline: "1px black"
}
}
}
},
series: [
{
name: "Two",
data: [[1532217600000, 1], [1532822400000, 0]],
color: "#41B6E6"
},
{
name: "Three",
data: [[1532217600000, 0], [1532822400000, 2]],
color: "#0072CE"
}
],
xAxis: {
tickWidth: 1,
title: {
enabled: false
},
labels: {
format: "{value: %b %e}"
},
max: 1533243166375,
min: 1530478366375,
type: "datetime"
},
yAxis: {
tickInterval: 20,
title: {
text: null
},
labels: {
format: "{value}%"
},
max: 100,
min: 0
},
tooltip: {}
});
Probably not the perfect solution, but you can create some customization to position the series labels. This is an example how to manually calculate the center of area in triangle shape:
Highcharts.wrap(Highcharts.Chart.prototype, 'drawSeriesLabels', function(proceed) {
proceed.apply(this, Array.prototype.slice.call(arguments, 1));
var chart = this,
plotTop = chart.plotTop,
plotLeft = chart.plotLeft,
series = chart.series,
height = chart.yAxis[0].height,
x1,
x2,
y1,
y2;
x1 = ((series[0].graphPath[1] + plotLeft) * 2 + series[0].graphPath[4] + plotLeft) / 3;
y1 = (height + plotTop + series[0].graphPath[2] + plotTop + series[0].graphPath[5] + plotTop) / 3;
x2 = (series[1].graphPath[1] + plotLeft + (series[1].graphPath[4] + plotLeft) * 2) / 3;
y2 = ((series[1].graphPath[2] + plotTop) * 2 + series[1].graphPath[5] + plotTop) / 3;
series[0].labelBySeries.attr({
x: x1,
y: y1,
align: 'center'
});
series[1].labelBySeries.attr({
x: x2,
y: y2,
align: 'center'
});
});
Live demo: http://jsfiddle.net/BlackLabel/34z8od5f/
Docs: https://www.highcharts.com/docs/extending-highcharts/extending-highcharts

How to use Highcharts to implement this dynamically shifting from right to left effect?

I'm using Highcharts to draw a graph with dynamic data.
I found this official demo.http://jsfiddle.net/vn9bk80j/
$(function () {
$(document).ready(function () {
Highcharts.setOptions({
global: {
useUTC: false
}
});
$('#container').highcharts({
chart: {
type: 'spline',
animation: Highcharts.svg, // don't animate in old IE
marginRight: 10,
events: {
load: function () {
// set up the updating of the chart each second
var series = this.series[0];
setInterval(function () {
var x = (new Date()).getTime(), // current time
y = Math.random();
series.addPoint([x, y], true, false);
}, 1000);
}
}
},
title: {
text: 'Live random data'
},
xAxis: {
type: 'datetime',
tickPixelInterval: 150
},
yAxis: {
title: {
text: 'Value'
},
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, 2);
}
},
legend: {
enabled: false
},
exporting: {
enabled: false
},
series: [{
name: 'Random data',
data: []
}]
});
});
});
<script src="https://code.highcharts.com/highcharts.js"></script>
<script src="https://code.highcharts.com/modules/exporting.js"></script>
<div id="container" style="min-width: 310px; height: 400px; margin: 0 auto"></div>
The graph window size is varing, it looks like
Howerver, I need graph window size to be fixed, data in this graph shifts from right to left as a whole from the beginning. Just like in the following pic.
How can I get the effects in picture 2 with Highcharts?
You can use null points to create empty space, and then just add pints with shift=true, see: http://jsfiddle.net/vn9bk80j/1/
function getEmptyData() {
var interval = 1000, // 1 second,
numberOfPoints = 50,
now = (new Date()).getTime(),
min = now - interval * numberOfPoints,
points = [];
while (min <= now) {
points.push([min, null]); // set null points
min += interval;
}
return points;
}
And method use case:
series: [{
name: 'Random data',
data: getEmptyData()
}]
shift=true example:
series.addPoint([x, y], true, true);

Highcharts > Positioning data labels between columns

I'm using Highcharts to show the % difference between the columns.
The labels above the columns represent that bars total. The % between the columns show a % change between each bar. I have positioned the x-axis OK, but the y-axis values are difficult. My aim is to:
Align % values to 50% on the y-Axis (half the height of the chart) and in between the columns so it shows a straight line of values. Currently these numbers are relative to the height of the bar column values.
http://jsfiddle.net/tellmehow/1sr9ab6d/15/
See an image here:
My code as follows.
$(function(){
var data = [1000,800,700,300,250,234,10,1,0,0];
function percent(data) {
var result = [];
for (var i=0; i<data.length -1; i++) {
if(data[i] === 0) {
result[data[i]] = 100;
} else {
result[data[i]] = 100 - (data[i] - data[i +1]) * 100 / data[i];
}
}
return result;
} //percent
$('#highcharts-panel').highcharts({
chart: {
type: 'column',
events: {
redraw: function(event) {
refreshArrowPos();
}
}
},
xAxis: {
categories: [{
text: "various...",
}]
},
yAxis: {
min: 0,
title: {
text: 'whatever'
}
},
tooltip: {
enabled: false,
followTouchMove: false
},
plotOptions: {
column: {
pointPadding: 0.2,
borderWidth: 0,
dataLabels: {
enabled: true
},
}, //col
series: {
marker: {
enabled: false
},
shadow:false,
borderWidth:0,
dataLabels:{
useHTML: true,
enabled:true,
formatter:function() {
var percents = percent(data);
return (Highcharts.numberFormat(this.y,0) + "<div class='dataPercent'>" + (this.y == data[data.length - 1] ? '' : Highcharts.numberFormat(percents[this.y]) + '%' + "<div class='arrow'></div>") + "</div>");
},
style: {
fontSize: "14px",
}
}
}
},
legend: {
enabled: false
},
series: [{
name: 'Total users',
data: data,
}],
}
);
function refreshArrowPos() {
$('.dataPercent').each (function(){
var colWidth = ($('#highcharts-panel').width() / data.length);
var colHeight = ($('#highcharts-panel').height() / data.length);
$(this).css({ left: ($(this).position().left + (colWidth / 2) - ($(this).width() / 4 )) + 'px',
top: ($(this).position().top + (colHeight / 2)) + 'px'
}); //end css
}); //dataPErcent fun
} //refreshArrowPos
refreshArrowPos();
});//highCharts Func
<div id="highcharts-pannel" class="funnelChart"></div>

How can I change the width of the bars in a highchart?

With a bar chart like this one, is is possible to change the width of the bars to represent another data attribute, say the weight of the fruits. The heavier the fruit is, the thicker the bar.
You play with the script here. I am open to other javascript plotting libraries that could do that as long as they are free.
$(function () {
var chart;
$(document).ready(function() {
chart = new Highcharts.Chart({
chart: {
renderTo: 'container',
type: 'column'
},
title: {
text: 'Column chart with negative values'
},
xAxis: {
categories: ['Apples', 'Oranges', 'Pears', 'Grapes', 'Bananas']
},
tooltip: {
formatter: function() {
return ''+
this.series.name +': '+ this.y +'';
}
},
credits: {
enabled: false
},
series: [{
name: 'John',
data: [5, 3, 4, 7, 2]
// I would like something like this (3.5, 6 etc is the width) :
// data: [[5, 3.4], [3, 6], [4, 3.4], [7, 2], [2, 5]]
}, {
name: 'Jane',
data: [2, -2, -3, 2, 1]
}, {
name: 'Joe',
data: [3, 4, 4, -2, 5]
}]
});
});
});​
pointWidth is what you require to set the width of the bars. try
plotOptions: {
series: {
pointWidth: 15
}
}
This display bars with the width of 15px. Play around here. Just made an edit to the already existing code.
I use a set of area charts to simulate a variable-width-column/bar-chart. Say, each column/bar is represented by a rectangle area.
See my fiddle demo (http://jsfiddle.net/calfzhou/TUt2U/).
$(function () {
var rawData = [
{ name: 'A', x: 5.2, y: 5.6 },
{ name: 'B', x: 3.9, y: 10.1 },
{ name: 'C', x: 11.5, y: 1.2 },
{ name: 'D', x: 2.4, y: 17.8 },
{ name: 'E', x: 8.1, y: 8.4 }
];
function makeSeries(listOfData) {
var sumX = 0.0;
for (var i = 0; i < listOfData.length; i++) {
sumX += listOfData[i].x;
}
var gap = sumX / rawData.length * 0.2;
var allSeries = []
var x = 0.0;
for (var i = 0; i < listOfData.length; i++) {
var data = listOfData[i];
allSeries[i] = {
name: data.name,
data: [
[x, 0], [x, data.y],
{
x: x + data.x / 2.0,
y: data.y,
dataLabels: { enabled: true, format: data.x + ' x {y}' }
},
[x + data.x, data.y], [x + data.x, 0]
],
w: data.x,
h: data.y
};
x += data.x + gap;
}
return allSeries;
}
$('#container').highcharts({
chart: { type: 'area' },
xAxis: {
tickLength: 0,
labels: { enabled: false}
},
yAxis: {
title: { enabled: false}
},
plotOptions: {
area: {
marker: {
enabled: false,
states: {
hover: { enabled: false }
}
}
}
},
tooltip: {
followPointer: true,
useHTML: true,
headerFormat: '<span style="color: {series.color}">{series.name}</span>: ',
pointFormat: '<span>{series.options.w} x {series.options.h}</span>'
},
series: makeSeries(rawData)
});
});
Fusioncharts probably is the best option if you have a license for it to do the more optimal Marimekko charts…
I've done a little work trying to get a Marimekko charts solution in highcharts. It's not perfect, but approximates the first Marimekko charts example found here on the Fusion Charts page…
http://www.fusioncharts.com/resources/chart-tutorials/understanding-the-marimekko-chart/
The key is to use a dateTime axis, as that mode provides you more flexibility for the how you distribute points and line on the X axis which provides you the ability to have variably sized "bars" that you can construct on this axis. I use 0-1000 second space and outside the chart figure out the mappings to this scale to approximate percentage values to pace your vertical lines. Here ( http://jsfiddle.net/miken/598d9/2/ ) is a jsfiddle example that creates a variable width column chart.
$(function () {
var chart;
Highcharts.setOptions({
colors: [ '#75FFFF', '#55CCDD', '#60DD60' ]
});
$(document).ready(function() {
var CATEGORY = { // number out of 1000
0: '',
475: 'Desktops',
763: 'Laptops',
1000: 'Tablets'
};
var BucketSize = {
0: 475,
475: 475,
763: 288,
1000: 237
};
chart = new Highcharts.Chart({
chart: {
renderTo: 'container',
type: 'area'
},
title: {
text: 'Contribution to Overall Sales by Brand & Category (in US$)<br>(2011-12)'
},
xAxis: {
min: 0,
max: 1000,
title: {
text: '<b>CATEGORY</b>'
},
tickInterval: 1,
minTickInterval: 1,
dateTimeLabelFormats: {
month: '%b'
},
labels: {
rotation: -60,
align: 'right',
formatter: function() {
if (CATEGORY[this.value] !== undefined) {
return '<b>' + CATEGORY[this.value] + ' (' +
this.value/10 + '%)</b>';
}
}
}
},
yAxis: {
max: 100,
gridLineWidth: 0,
title: {
text: '<b>% Share</b>'
},
labels: {
formatter: function() {
return this.value +'%'
}
}
},
tooltip: {
shared: true,
useHTML: true,
formatter: function () {
var result = 'CATEGORY: <b>' +
CATEGORY[this.x] + ' (' + Highcharts.numberFormat(BucketSize[this.x]/10,1) + '% sized bucket)</b><br>';
$.each(this.points, function(i, datum) {
if (datum.point.y !== 0) {
result += '<span style="color:' +
datum.series.color + '"><b>' +
datum.series.name + '</b></span>: ' +
'<b>$' + datum.point.y + 'K</b> (' +
Highcharts.numberFormat(
datum.point.percentage,2) +
'%)<br/>';
}
});
return (result);
}
},
plotOptions: {
area: {
stacking: 'percent',
lineColor: 'black',
lineWidth: 1,
marker: {
enabled: false
},
step: true
}
},
legend: {
layout: 'vertical',
align: 'right',
verticalAlign: 'top',
x: 0,
y: 100,
borderWidth: 1,
title: {
text : 'Brand:'
}
},
series: [ {
name: 'HP',
data: [
[0,298],
[475,109],
[763,153],
[1000,153]
]
}, {
name: 'Dell',
data: [
[0,245],
[475,198],
[763,120],
[1000,120]
]
}, {
name: 'Sony',
data: [
[0,335],
[475,225],
[763,164],
[1000,164]
]
}]
},
function(chart){
// Render bottom line.
chart.renderer.path(['M', chart.plotLeft, chart.plotHeight + 66, 'L', chart.plotLeft+chart.plotWidth, chart.plotHeight + 66])
.attr({
'stroke-width': 3,
stroke: 'black',
zIndex:50
})
.add();
for (var category_idx in CATEGORY) {
chart.renderer.path(['M', (Math.round((category_idx / 1000) * chart.plotWidth)) + chart.plotLeft, 66, 'V', chart.plotTop + chart.plotHeight])
.attr({
'stroke-width': 1,
stroke: 'black',
zIndex:4
})
.add();
}
});
});
});
It adds an additional array to allow you to map category names to second tic values to give you a more "category" view that you might want. I've also added code at the bottom that adds vertical dividing lines between the different columns and the bottom line of the chart. It might need some tweaks for the size of your surrounding labels, etc. that I've hardcoded in pixels here as part of the math, but it should be doable.
Using a 'percent' type accent lets you have the y scale figure out the percentage totals from the raw data, whereas as noted you need to do your own math for the x axis. I'm relying more on a tooltip function to provide labels, etc than labels on the chart itself.
Another big improvement on this effort would be to find a way to make the tooltip hover area and labels to focus and be centered and encompass the bar itself instead of the right border of each bar that it is now. If someone wants to add that, feel free to here.
If I got it right you want every single bar to be of different width. I had same problem and struggled a lot to find a library offering this option. I came to the conclusion - there's none.
Anyways, I played with highcharts a little, got creative and came up with this:
You mentioned that you'd like your data to look something like this: data: [[5, 3.4], [3, 6], [4, 3.4]], with the first value being the height and the second being the width.
Let's do it using the highcharts' column graph.
Step 1:
To better differentiate the bars, input each bar as a new series. Since I generated my data dynamically, I had to assign new series dynamically:
const objects: any = [];
const extra = this.data.length - 1;
this.data.map((range) => {
const obj = {
type: 'column',
showInLegend: false,
data: [range[1]],
animation: true,
borderColor: 'black',
borderWidth: 1,
color: 'blue'
};
for (let i = 0; i < extra; i++) {
obj.data.push(null);
}
objects.push(obj);
});
this.chartOptions.series = objects;
That way your different series would look something like this:
series: [{
type: 'column',
data: [5, 3.4]
}, {
type: 'column',
data: [3, 6]
}, {
type: 'column',
data: [4, 3.4]
}]
Step 2:
Assign this as plot options for highcharts:
plotOptions: {
column: {
pointPadding: 0,
borderWidth: 0,
groupPadding: 0,
shadow: false
}
}
Step 3:
Now let's get creative - to have the same starting point for all bars, we need to move every single one to the graph's start:
setColumnsToZero() {
this.data.map((item, index) => {
document.querySelector('.highcharts-series-' + index).children[0].setAttribute('x', '0');
});
}
Step 4:
getDistribution() {
let total = 0;
// Array including all of the bar's data: [[5, 3.4], [3, 6], [4, 3.4]]
this.data.map(item => {
total = total + item[0];
});
// MARK: Get xAxis' total width
const totalWidth = document.querySelector('.highcharts-axis-line').getBoundingClientRect().width;
let pos = 0;
this.data.map((item, index) => {
const start = item[0];
const width = (start * totalWidth) / total;
document.querySelector('.highcharts-series-' + index).children[0].setAttribute('width', width.toString());
document.querySelector('.highcharts-series-' + index).children[0].setAttribute('x', pos.toString());
pos = pos + width;
this.getPointsPosition(index, totalWidth, total);
});
}
Step 4:
Let's get to the xAxis' points. In the first functions modify the already existing points, move the last point to the end of the axis and hide the others. In the second function we clone the last point, modify it to have either 6 or 3 total xAxis points and move each of them to the correct position
getPointsPosition(index, totalWidth, total) {
const col = document.querySelector('.highcharts-series-' + index).children[0];
const point = (document.querySelector('.highcharts-xaxis-labels').children[index] as HTMLElement);
const difference = col.getBoundingClientRect().right - point.getBoundingClientRect().right;
const half = point.getBoundingClientRect().width / 2;
if (index === this.data.length - 1) {
this.cloneNode(point, difference, totalWidth, total);
} else {
point.style.display = 'none';
}
point.style.transform = 'translateX(' + (+difference + +half) + 'px)';
point.innerHTML = total.toString();
}
cloneNode(ref: HTMLElement, difference, totalWidth, total) {
const width = document.documentElement.getBoundingClientRect().width;
const q = total / (width > 1000 && ? 6 : 3);
const w = totalWidth / (width > 1000 ? 6 : 3);
let val = total;
let valW = 0;
for (let i = 0; i < (width > 1000 ? 6 : 3); i++) {
val = val - q;
valW = valW + w;
const clone = (ref.cloneNode(true) as HTMLElement);
document.querySelector('.highcharts-xaxis-labels').appendChild(clone);
const half = clone.getBoundingClientRect().width / 2;
clone.style.transform = 'translateX(' + (-valW + difference + half) + 'px)';
const inner = Math.round(val * 100) / 100;
clone.innerHTML = inner.toString();
}
}
In the end we have a graph looking something like this (not the data from this given example, but for [[20, 0.005], [30, 0.013333333333333334], [20, 0.01], [30, 0.005555555555555555], [20, 0.006666666666666666]] with the first value being the width and the second being the height):
There might be some modifications to do to 100% fit your case. F.e. I had to adjust the xAxis' points a specific starting and end point - I spared this part.

Categories