javascript - How to hide bar but keep datalabels HighCharts
问题描述
How to hide bar but keep datalabels HighCharts , i have 3 bars,
- Target
- Realization
- Percentage
i supposed to show only the first and the second bar,with only 1 datalabels which is percentage. so i made quite a trick to my code
Here is the sample :
var target = [50,100];
var realization = [10,40];
var percentage = [];
for(i = 0;i < target.length; i++) {
var divide = (realization[i] / target[i]) * 100;
if (divide == Number.POSITIVE_INFINITY || divide == Number.NEGATIVE_INFINITY || isNaN(divide)) {
percentage.push(0);
} else {
percentage.push(divide);
}
}
series: [
{
name: 'Target )',
color :' #009933',
data: target,
},
// i put the trick on the second series where i tricked it
{
name: 'Percentage',
data: percentage,
color :'rgba(255, 255, 255, .4)',
showInLegend: false,
pointWidth :1,
lineColor: 'transparent',
marker: {
fillColor: 'transparent',
states: {
hover: {
enabled: false
}
}
}
},
{
name: 'Realization',
color : '#00ff00',
data: percentage,
}]
it will look like this
The trick i used is make the percentage on the middle,and change the bar color into transparent.
This is the result i was expecting
This is my full code :
https://jsfiddle.net/xanrdswq/
This is only temporary solution i have.
解决方案
It can be simply achieved using Highchart.SVGRenderer.text
method that allows drawing a custom text. Labels can be added in render event callback or chart callback (when the chart width is fixed).
Check code and demo posted below and let me know if something is not clear for you.
Code:
chart: {
type: 'bar',
events: {
render: function() {
const chart = this,
xAxis = chart.xAxis[0],
yAxis = chart.yAxis[0],
offsetX = 5;
let customElems = chart.customElems || [],
y,
x,
element;
if (customElems.length) {
customElems.forEach(elem => {
elem.destroy();
});
customElems.length = 0;
}
chart.series[0].points.forEach((point, i) => {
x = yAxis.toPixels(point.y) + offsetX;
y = xAxis.toPixels(point.x);
element = chart.renderer.text(`${percentage[i]} %`, x, y).css({
fill: '#000'
}).add().toFront();
customElems.push(element);
});
chart.customElems = customElems;
}
}
}
Demo:
API reference:
推荐阅读
- python - “Dash plotly”:我在将两个输入连接到输出时遇到问题,而且 bas x 轴也没有排序和正确分类
- ruby - 使用 rspec 测试 ruby 脚本很热门
- firebase - 检索数据时出现异常:- 未布置 RenderBox
- google-apps-script - 为什么“category:social”在 GMail UI 搜索中使用,但在 GmailApp.search("category:social", 0, 500) 中不起作用
- python - 用不稳定的时间序列模型拟合时间序列
- flutter - 如何在snackbar中实现撤消功能,以便在flutter中的sqlite中进行硬删除和软删除?
- node.js - 错误:不能在模块外使用导入语句
- php - php文件不显示任何输出
- c# - 两个字符串之间的正则表达式字符串包括括号
- python - 使用 python 从连接到另一个容器的容器创建一个新的 kafka 主题