Highcharts Line Chart, display series name at the end of line series - javascript

We have requirement for line chart as below. We are using highcharts. Our requirement is that chart should display series name at the end of line as displayed in below images.
How can we achieve this?

As an alternative to the renderer(), I find it convenient to use the dataLabels for this purpose.
The idea being to disable dataLabels in the plotOptions, but define the position and format anyway.
Then enable the dataLabels for the last point in each series' data array.
Example:
plotOptions: {
series: {
dataLabels: {
enabled: false,
crop: false,
overflow: 'none',
align: 'left',
verticalAlign: 'middle',
formatter: function() {
return '<span style="color:'+this.series.color+'">'+this.series.name+'</span>';
}
}
}
}
Fiddle:
http://jsfiddle.net/jlbriggs/pgo7pedn/
Output example:

Get last point, which has plotX and plotY properties, then draw your labels with render.
const options = {
chart: {
events: {
load() {
const chart = this
const series = chart.series
series.forEach((s) => {
const len = s.data.length
const point = s.data[len - 1]
console.log(point)
chart.renderer.text(
point.series.name,
point.plotX + chart.plotLeft + 10,
point.plotY + chart.plotTop - 10
)
.attr({
zIndex: 5
})
.add()
})
}
}
},
xAxis: {
max: 5
},
series: [{
data: [30, 70, 50, 90]
}, {
data: [60, 100, 80, 120]
}, {
data: [80, 150, 90, 180]
}]
}
const chart = Highcharts.chart('container', options)
Live example:
https://jsfiddle.net/479vdhm3/

Related

Style dash in highchart graphic

I'm trying to change the line style of a chart, but I'm not getting it. I'm
looking to change the black line in the middle of the chart, to the style "DASH"
I already put the "dashStyle: 'dash'" in several places, but without success.
The example is the one of the highcharts
I'm trying to change the line style of a chart, but I'm not getting
it.
It is not possible because what you call line is actually an SVG rectangle element. That's why it can't be dashed.
However, you can achieve what you want by adding some custom logic and using Highcharts.SVGRenderer. Simply remove default rectangle graphic of each series point and render several rectangles with breaks to create a dashed line. Check the code and demo posted below.
Code:
Highcharts.setOptions({
chart: {
inverted: true,
marginLeft: 135,
type: 'bullet',
events: {
render: function() {
var chart = this,
point = chart.series[0].points[0],
width = point.shapeArgs.height,
height = point.shapeArgs.width,
x = chart.plotLeft,
xEnd = x + width,
y = chart.plotTop + point.shapeArgs.x,
dashWidth = 15,
dashBreakWidth = 5,
dashColor = '#000',
dashElem,
dashAmount,
realDashBreakWidth;
if (chart.dashedColl) {
chart.dashedColl.forEach(function(oldDashElem) {
oldDashElem.destroy();
});
}
point.graphic.element.remove();
chart.dashedColl = [];
dashAmount = Math.floor(width / (dashWidth + dashBreakWidth));
realDashBreakWidth = (width - dashAmount * dashWidth) / (dashAmount - 1);
while (x < xEnd) {
dashElem = chart.renderer.rect(x, y, dashWidth, height)
.attr({
fill: dashColor
})
.add()
.toFront();
chart.dashedColl.push(dashElem);
x += dashWidth + realDashBreakWidth;
}
}
}
},
title: {
text: null
},
legend: {
enabled: false
},
yAxis: {
gridLineWidth: 0
},
plotOptions: {
series: {
pointPadding: 0.25,
borderWidth: 0,
color: 'red',
targetOptions: {
width: '200%'
}
}
},
credits: {
enabled: false
},
exporting: {
enabled: false
}
});
Demo:
https://jsfiddle.net/BlackLabel/7azfso1r/
API reference:
https://api.highcharts.com/class-reference/Highcharts.SVGRenderer#rect
https://api.highcharts.com/class-reference/Highcharts.Point#remove
https://api.highcharts.com/highcharts/chart.events.render

Drawing a small vertical line on top of chart using High charts by specifying end coordinates

I am new to High Charts for drawing charts. My requirement is to draw a small vertical line on top of already drawn chart by specifying end coordinates. I can easily draw one using the JqPlot plugin and the image is given below.
The options I have used in JqPlot is
canvasOverlay: {
show: true,
objects: [
{line: {
name: 'stack-overflow',
lineWidth: 6,
start: [8, 0.5],
stop:[8, 0.7],
color: 'rgb(100, 55, 124)',
shadow: false
}}
]
}
On some research I have found that I can use plotLines in High charts
Stackoverflow Post
I have tried this option but it draws a full length red vertical line and I don't see any option to restrict the length of the line.
The code I have used is given below
xAxis: {
min: 0,
max: 35,
tickInterval: 5,
title: {text: "Time"},
plotLines: [{
color: 'red',
width: 5,
value: 5.5
}]
}
UPDATE:
JSFiddle link is given below
JSFIddle
Am I missing something or do I need to try some other options
You could use the Highcharts renderer option
function (chart) {
var lineStartXposition2 = lineStartXposition + chart.plotLeft + 10,
lineStartYposition2 = lineStartYposition + chart.plotTop + 10,
lineEndXposition2 = lineEndXposition + chart.plotLeft + 10,
lineEndYposition2 = lineEndYposition + chart.plotTop + 10;
chart.renderer.path(['M', positionX, positionY, 'L', positionX, positionEnd])
.attr({
'stroke-width': 2,
stroke: 'red'
})
.add();
});
Update 3 : New fiddle using point coordinates and variables
Fiddle
I hope the following link will help you
chart.addSeries({
name: 'Line Marker Values',
type:'scatter',
marker: {
symbol:'hline',
lineWidth:2,
lineColor:'rgba(253,0,154,0.9)',
radius:12
},
data: [32,35,37,28,42,35,27]
});
click here
You can use appropriately configured scatter series for this.
var chart = Highcharts.chart('container', {
series: [{
data: [1, 3, 4, 5, 1]
}, {
tooltip: {
pointFormat: null // don't dispaly tooltip
},
states: {
hover: {
enabled: false
}
},
type: 'scatter', // points don't need to be sorted
lineWidth: 3,
marker: {
enabled: false
},
showInLegend: false,
data: [
[2, 3], [2, 5]
]
}]
});
Live demo: http://jsfiddle.net/kkulig/gab2ow7f/

Highcharts how to create legends based on the value of points

I know exactly how to enable legend in Highcharts, but the problem is how to create legends based on the value of the points from the same series since every legend is used to symbolize a series(a collection of points).
There's is a picture(chart type: waterfall) I draw in excel below illustrating what I want, you can see clearly that orange color legend stands for gaining, while blue one stands for loss, but how do I achieve this in Highcharts?
I've searched a lot but ended with disappointment, please help.
One way to do this is with a dummy series.
Create an extra series, with the name and color that you want, with an empty data array:
series: [{
name: 'Actual Series',
data: [...data, with points colored as needed...]
}, {
grouping: false,
name: 'Dummy Series',
color: 'chosen color',
data: []
}]
You'll also want to set grouping to false, so that the dummy series does not take up extra blank space on the plot.
Fiddle:
http://jsfiddle.net/jlbriggs/vjd3p4s0/
(also, the same thing using the Waterfall demo: http://jsfiddle.net/jlbriggs/7vtbzh53/ )
Another way to do this would be to create your own legend, outside of the chart.
Either way, you will lose the functionality of clicking the legend to show/hide the series of for the orange columns. You would have to build a more complex function to edit the data on legendItemClick if you that ability is important to you.
Solution for edited question. You can map your data to two series and set stacking to 'normal'.
const data = [10, 20, -10, 20, 10, -10];
const dataPositive = data.map(v => v >= 0 ? v : 0);
const dataNegative = data.map(v => v < 0 ? v : 0);
const options = {
chart: {
type: 'column'
},
series: [{
color: 'blue',
data: dataPositive,
stacking: 'normal'
}, {
color: 'orange',
data: dataNegative,
stacking: 'normal'
}]
}
const chart = Highcharts.chart('container', options);
Live example:
https://jsfiddle.net/j2o5bdgs/
[EDIT]
Solution for waterfall chart:
const data = [10, 20, -30];
const colors = Highcharts.getOptions().colors;
const options = {
chart: {
type: 'waterfall'
},
series: [{
// Single series simulating 2 series
data: data.map(v => v < 0 ? {
y: v,
color: colors[0]
} : {
y: v,
color: colors[3]
}),
stacking: 'normal',
showInLegend: false
}, {
// Positive data serie
color: colors[3],
data: [10, 20, 0],
visible: false,
stacking: 'normal',
showInLegend: false
}, {
// Negative data serie
color: colors[0],
data: [0, 0, -30],
visible: false,
stacking: 'normal',
showInLegend: false
}, {
// Empty serie for legend item
name: 'Series 1',
color: colors[3],
stacking: 'normal',
events: {
legendItemClick: function(e) {
const series = this.chart.series;
const invisibleCount = document.querySelectorAll('.highcharts-legend-item-hidden').length;
if (this.visible) {
if (invisibleCount === 1) {
series[0].hide();
series[1].hide();
series[2].hide();
} else {
series[0].hide();
series[2].show();
}
} else if (invisibleCount === 2) {
series[0].hide();
series[1].show();
} else {
series[0].show();
series[2].hide();
}
}
}
}, {
// Empty serie for legend item
name: 'Series 2',
color: colors[0],
stacking: 'normal',
events: {
legendItemClick: function(e) {
const series = this.chart.series;
const invisibleCount = document.querySelectorAll('.highcharts-legend-item-hidden').length;
if (this.visible) {
if (invisibleCount === 1) {
// hide all
series[0].hide();
series[1].hide();
series[2].hide();
return;
}
series[0].hide();
series[1].show();
} else {
if (invisibleCount === 2) {
series[0].hide();
series[2].show();
return;
}
series[0].show();
series[1].hide();
}
}
}
}]
}
const chart = Highcharts.chart('container', options);
Live example:
https://jsfiddle.net/2uszoLop/

How do I remove padding from both sides of Highcharts area category chart?

There's too much padding on either side of the area chart and minPadding/maxPadding doesn't work with categories.
I want the area chart to start and end without any padding.
My code is below:
http://jsfiddle.net/nx4xeb4k/1/
$('#container').highcharts({
chart: {
type: 'area',
inverted: false
},
title: {
text: 'Too Much Padding On Either Side'
},
plotOptions: {
series: {
fillOpacity: 0.1
}
},
xAxis: {
type: 'category'
},
yAxis: {
title: {
text: 'Data Point'
}
},
legend: {
enabled: false
},
tooltip: {
pointFormat: '<b>{point.y}</b> points'
},
series: [{
name: 'Visits',
data: [
["Monday", 58],
["Tuesday", 65],
["Wednesday", 55],
["Thursday", 44],
["Friday", 56],
["Saturday", 65],
["Sunday", 69]
],
dataLabels: {
enabled: false,
rotation: -90,
color: '#FFFFFF',
align: 'right',
format: '{point.y:.1f}',
y: 10,
style: {
fontSize: '14px',
fontFamily: 'Verdana, sans-serif'
}
}
}]
});
A colleague of mine solved this very situation for some of my charts. Their solution was to remove the type: 'category' from the x-axis (making it a linear type instead) and instead replace the axis labels from an array.
Here's what's been changed:
First, I added an array of your x-axis labels.
var categoryLabels = ["Monday","Tuesday","Wednesday","Thursday","Friday",
"Saturday","Sunday"];
Next, I updated your series values to hold only the y-axis values.
series: [{
name: 'Visits',
data: [58, 65, 55, 44, 56, 65, 69],
Then, for your x-axis, I included a formatter function to pull in the labels from the array as substitutes for the default linear values.
xAxis: {
labels: {
formatter: function(){
return categoryLabels[this.value];
}
}
},
Lastly, I updated the tooltip options to show the values from the labels array.
tooltip: {
formatter: function () {
return categoryLabels[this.x] + ': ' + Highcharts.numberFormat(this.y,0);
}
},
I updated your fiddle with this tweaks: http://jsfiddle.net/brightmatrix/nx4xeb4k/4/
I hope you'll find this solution as useful as I have!
According to API, the default value of highcharts.xAxis.tickmarkPlacement is between and this is why the point of each category drops between two ticks on xAxis in your chart.
By setting highcharts.xAxis.tickmarkPlacement to on and playing around the value of highcharts.xAxis.min and highcharts.xAxis.max like this, you should be able to achieve what you want.
You can declare the min / max values to fix the problem.
var categoryLabels = ["Monday","Tuesday","Wednesday","Thursday","Friday","Saturday","Sunday"];
//....
xAxis: {
min: 0.49,
max: categoryLabels.length - 1.49,
categories: categoryLabels,
type: 'category'
},
Example:
http://jsfiddle.net/fo04m7k7/

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