I'm trying to create something similar to the image below. Where each column has a heading with it.
I know that chart.renderer.text can be used to create & place custom text on chart. However, I'm unable to find a way to fetch the column/node coordinates data(x,y) which would help me place them.
Also is there a programmatic way to do this task. For example, a function that fetches all the columns coordinates and populates all the headings from an existing list.
To summarize:
How to fetch a columns (x,y) Coordinates?
How to dynamically place headings for all columns from a list?
Image
You can get the required coordinates and place the headers in render event, for example:
events: {
render: function() {
var chart = this,
series = chart.series[0],
columns = series.nodeColumns,
isFirst,
isLast,
xPos;
if (!series.customHeaders) {
series.customHeaders = [];
}
columns.forEach(function(column, i) {
xPos = column[0].nodeX + chart.plotLeft;
isFirst = i === 0;
isLast = i === columns.length - 1;
if (!series.customHeaders[i]) {
series.customHeaders.push(
chart.renderer.text(
headers[i],
xPos,
80
).attr({
translateX: isFirst ? 0 : (
isLast ?
series.options.nodeWidth :
series.options.nodeWidth / 2
),
align: isFirst ? 'left' : (
isLast ? 'right' : 'center'
)
}).add()
)
} else {
series.customHeaders[i].attr({
x: xPos
});
}
});
}
}
Live demo: https://jsfiddle.net/BlackLabel/6Lvdufbp/
API Reference:
https://api.highcharts.com/highcharts/chart.events.render
https://api.highcharts.com/class-reference/Highcharts.SVGRenderer#text
Related
I have a highcharts sankey diagram with two sides:
There are situations where some of my nodes have empty links (=with 0 weight). I would like the node to being displayed despite having no link from or to it.
Any chance I can achieve this?
I read on this thread that I have to fake it with weight=1 connexions, I could make the link transparent, and twitch the tooltip to hide those, but that's very painful for something that feels pretty basic.
Maybe a custom call of the generateNode call or something?
Thanks for the help
You can use the following wrap to show a node when the weight is 0.
const isObject = Highcharts.isObject,
merge = Highcharts.merge
function getDLOptions(
params
) {
const optionsPoint = (
isObject(params.optionsPoint) ?
params.optionsPoint.dataLabels : {}
),
optionsLevel = (
isObject(params.level) ?
params.level.dataLabels : {}
),
options = merge({
style: {}
}, optionsLevel, optionsPoint);
return options;
}
Highcharts.wrap(
Highcharts.seriesTypes.sankey.prototype,
'translateNode',
function(proceed, node, column) {
var translationFactor = this.translationFactor,
series = this,
chart = this.chart,
options = this.options,
sum = node.getSum(),
nodeHeight = Math.max(Math.round(sum * translationFactor),
this.options.minLinkWidth),
nodeWidth = Math.round(this.nodeWidth),
crisp = Math.round(options.borderWidth) % 2 / 2,
nodeOffset = column.sankeyColumn.offset(node,
translationFactor),
fromNodeTop = Math.floor(Highcharts.pick(nodeOffset.absoluteTop, (column.sankeyColumn.top(translationFactor) +
nodeOffset.relativeTop))) + crisp,
left = Math.floor(this.colDistance * node.column +
options.borderWidth / 2) + Highcharts.relativeLength(node.options.offsetHorizontal || 0,
nodeWidth) +
crisp,
nodeLeft = chart.inverted ?
chart.plotSizeX - left :
left;
node.sum = sum;
proceed.apply(this, Array.prototype.slice.call(arguments, 1));
if (1) {
// Draw the node
node.shapeType = 'rect';
node.nodeX = nodeLeft;
node.nodeY = fromNodeTop;
let x = nodeLeft,
y = fromNodeTop,
width = node.options.width || options.width || nodeWidth,
height = node.options.height || options.height || nodeHeight;
if (chart.inverted) {
x = nodeLeft - nodeWidth;
y = chart.plotSizeY - fromNodeTop - nodeHeight;
width = node.options.height || options.height || nodeWidth;
height = node.options.width || options.width || nodeHeight;
}
// Calculate data label options for the point
node.dlOptions = getDLOptions({
level: (this.mapOptionsToLevel)[node.level],
optionsPoint: node.options
});
// Pass test in drawPoints
node.plotX = 1;
node.plotY = 1;
// Set the anchor position for tooltips
node.tooltipPos = chart.inverted ? [
(chart.plotSizeY) - y - height / 2,
(chart.plotSizeX) - x - width / 2
] : [
x + width / 2,
y + height / 2
];
node.shapeArgs = {
x,
y,
width,
height,
display: node.hasShape() ? '' : 'none'
};
} else {
node.dlOptions = {
enabled: false
};
}
}
);
Demo:
http://jsfiddle.net/BlackLabel/uh6fp89j/
In the above solution, another node arrangement would be difficult to achieve and may require a lot of modifications beyond our scope of support.
You can consider using mentioned "tricky solution", since might return a better positioning result. This solution is based on changing 0 weight nodes on the chart.load() event and converting the tooltip as well, so it may require adjustment to your project.
chart: {
events: {
load() {
this.series[0].points.forEach(point => {
if (point.weight === 0) {
point.update({
weight: 0.1,
color: 'transparent'
})
}
})
}
}
},
tooltip: {
nodeFormatter: function() {
return `${this.name}: <b>${Math.floor(this.sum)}</b><br/>`
},
pointFormatter: function() {
return `${this.fromNode.name} → ${this.toNode.name}: <b>${Math.floor(this.weight)}</b><br/>`
}
},
Demo:
http://jsfiddle.net/BlackLabel/0dqpabku/
When I'm drawing BOX Plot chart with Highchart like this : JSFiddle
chart: {
type: 'boxplot',
}
where category 2 "Merchant 2" is shown on x-axis even though we don't have data for it.
How can we avoid rendering categories on x-axis when they don't have data in box plot ?
Thank you
There's no built in mechanism in Highcharts that'll filter out and hide "unused" categories.
Workaround:
breaks functionality allows to hide regions on axes. Here's an algorithm that finds the categories that don't have any points above them and applies breaks:
render: function() {
if (redrawEnabled) {
redrawEnabled = false;
var emptyCategories = [],
series = this.series,
xAxis = this.xAxis[0],
categories = xAxis.categories.slice(),
categoryFlags = new Array(categories.length).fill(false), // indicates if any point has a value for category with the given index
breaks = [],
correspondingPoint;
// find out which categories are 'used'
for (var i = 0; i < categories.length; i++) {
for (var ii = 0; ii < series.length; ii++) {
if (!series[ii].visible) {
continue;
}
correspondingPoint = series[ii].data.find((point) => point.x === i);
if (correspondingPoint) {
categoryFlags[i] = true;
break;
}
}
}
// create and apply breaks
categoryFlags.forEach(function(flag, index) {
if (!flag) {
breaks.push({
from: index - 0.5,
to: index + 0.5
});
}
});
//console.log(breaks)
xAxis.update({
breaks: breaks
});
}
redrawEnabled = true;
}
Live demo: http://jsfiddle.net/BlackLabel/fubwdm4x/
The key to understand how this solution works is that the categories are basically just information how to format axis' labels and position ticks. The tickInterval is always 1 and ticks are moved -0.5 to the left. So if you have categories like this: ['Category 1', 'Category 2', 'Category 3'] the positions of ticks are: -0.5, 0.5, 1.5 and 2.5.
API reference: https://api.highcharts.com/highcharts/yAxis.breaks
When exporting scatter plot / bubble chart data as CSV or XLS, it is missing key information, see for example: http://jsfiddle.net/11fum86u/
This is the data (extract):
series: [{
data: [
{ x: 95, y: 95, z: 13.8, name: 'BE', country: 'Belgium' },
And the axis titles are in the tooltip (but perhaps needs to be defined elsewhere):
tooltip: {
pointFormat: '<tr><th colspan="2"><h3>{point.country}</h3></th></tr>' +
'<tr><th>Fat intake:</th><td>{point.x}g</td></tr>' +
'<tr><th>Sugar intake:</th><td>{point.y}g</td></tr>' +
'<tr><th>Obesity (adults):</th><td>{point.z}%</td></tr>',
What is missing in the default export is (i) labels for y and z axis, and (ii) the names of the bubbles (in this example, country codes/names)
I was wondering how I might be able to add this information to the export.
Actually there's no z axis in bubble charts. It's quite confusing, because all points have z property. This property serves to compute the bubble size so no additional axis is needed, because everything is in 2d. zAxis is used in 3d charts.
Please refer to this live working example: http://jsfiddle.net/kkulig/udtr0emL/
You can handle first row labels via columnHeaderFormatter (http://api.highcharts.com/highcharts/exporting.csv.columnHeaderFormatter):
exporting: {
csv: {
columnHeaderFormatter: function(item, key, keyLength) {
if (item.axisTitle) {
return item.axisTitle.textStr; // x axis label
} else if (key === 'y') {
return item.yAxis.axisTitle.textStr; // y axis label
} else if (key === 'z') {
return 'Obesity (adults)'; // z axis label
}
}
}
}
To add another column (countries) added following pieces of code in these three core functions:
1. Highcharts.Chart.prototype.getDataRows
// add original point reference
rows[key].point = point;
2. Highcharts.Chart.prototype.getCSV
// Add point name and header
csv += itemDelimiter;
var point = row['point'];
if (point) {
csv += point.name
} else {
csv += "Country"
}
3. Highcharts.Chart.prototype.getTable (for XLS)
var point = row['point'],
val;
if (point) {
val = point.name;
} else {
val = "Country";
}
html += '<' + tag + ' class="text">' +
(val === undefined ? '' : val) + '</' + tag + '>';
All functions are available in export-data.src.js in this directory: https://github.com/highcharts/highcharts/tree/b4b4221b19a3a50d9ed613b6f50b12f0afcc7d06/js/modules
I built a widget with multiple y Axes very similar to the official sample here: http://www.highcharts.com/stock/demo/candlestick-and-volume
I'm trying to have some sort of visual separation between the chart panes, either by
applying a special style to the maximum grid line for each pane, or
adding a horizontal line in the whitespace between the panes
The only approach i got working is using PlotLines, but I'd rather have a separator that's independent of zoom levels. Any ideas on how to achieve this?
Use Renderer to draw a path between y axes.
function drawSeparator() {
let separator = this.separator;
const options = this.options.chart.separator;
if (options && options.enabled) {
if (!separator) {
this.separator = separator = this.renderer.path({
d: 'M 0 0',
'stroke-width': options.width === undefined ? 1 : options.width,
stroke: options.color || 'black'
}).add();
}
const topAxisBottom = this.yAxis[0].top + this.yAxis[0].height;
const bottomAxisTop = this.yAxis[1].top;
const y = topAxisBottom + (bottomAxisTop - topAxisBottom) / 2;
separator.attr({
d: `M 0 ${y} L ${this.chartWidth} ${y}`
});
}
}
Call the method on load/redraw event
chart: {
events: {
load: drawSeparator,
redraw: drawSeparator
},
separator: {
enabled: true,
width: 3,
color: 'blue'
}
},
You can modify the path's d attribute, the path starts from axis.left and stops on axis.left + axis.width
Live example and output
http://jsfiddle.net/L11uqxgq/
I have an areaspline with only one series. The design calls for drawing x-axis gridlines that touch the series and don't extend beyond that. Is it possible to do this? Here's my code to configure the gridlines:
xAxis: {
gridLineWidth: 1,
tickAmount: 30,
lineWidth: 0,
labels: {
enabled: false
},
minPadding: 0
},
Another option (other then 2 mentioned by jlbriggs in a comment on the question) might be to extend Highcharts and change paths of grid lines in a wrapper like:
(function(H) {
var UNDEFINED;
H.wrap(H.Tick.prototype, 'render', function(p) {
p.apply(this, [].slice.call(arguments, 1)); //run original function
if (this.axis.isXAxis && this.gridLine) {
var point = this.axis.series[0].options.data[this.pos],
d = this.gridLine.attr('d').split(' ');
if (point !== UNDEFINED) {
d[2] = this.axis.chart.yAxis[0].toPixels(point);
d = d.join(' ');
} else {
d = ''; //remove if not crossing any point
}
this.gridLine.attr({
d: d
});
}
});
})(Highcharts)
Example: http://jsfiddle.net/69f5z3us/
If a grid line is not crossing any point, then the grid line is removed, but you could change that part of the code if you want to.