javascript - 如何使用 HightCharts 将两个数据标签添加到条形图中
问题描述
我想在每个栏上显示两个标签,一个在栏内,另一个在栏顶部。内部表示数量,上部表示该值占总数的百分比。
dados = [
{
name: "January",
y: 40,
},
{
name: "February",
y: 10,
},
{
name: "March",
y: 7,
},
{
name: "April",
y: 5,
},
{
name: "June",
y: 4,
},
{
name: "July",
y: 1,
},
{
name: "August",
y: 7,
},
{
name: "September",
y: 17,
},
{
name: "October",
y: 12,
},
{
name: "November",
y: 15,
},
{
name: "December",
y: 10,
}
];
//percentage code
Array.prototype.sum = function (prop) {
var total = 0
for ( var i = 0, _len = this.length; i < _len; i++ ) {
total += this[i][prop]
}
return total
}
var soma = dados.sum("y");
var total = dados.length;
for (var i = 0; i < dados.length; i++){
dados[i]['p'] = dados[i].y*100/soma;
}
//
Highcharts.chart('container', {
chart: {
type: 'column'
},
title: {
text: 'Quantidade de fatos históricos por período'
},
xAxis: {
type: 'category',
labels: {
rotation: -45,
style: {
fontSize: '13px',
fontFamily: 'Verdana, sans-serif'
}
}
},
yAxis: {
min: 0,
title: {
text: 'Fatos históricos (quantidade)'
}
},
legend: {
enabled: false
},
tooltip: {
pointFormat: 'Quantidade em {point.name}: <b>{point.y} ({point.p:.2f} % )</b>'
},
series: [{
name: 'Population',
data: dados,
dataLabels: {
enabled: true,
rotation: -90,
color: '#FFFFFF',
align: 'right',
format: '{point.y}', // one decimal
y: 10, // 10 pixels down from the top
style: {
fontSize: '13px',
fontFamily: 'Verdana, sans-serif'
}
}
}]
});
<script src="https://code.highcharts.com/highcharts.js"></script>
<script src="https://code.highcharts.com/modules/exporting.js"></script>
<script src="https://code.highcharts.com/modules/export-data.js"></script>
<script src="https://code.highcharts.com/modules/accessibility.js"></script>
<figure class="highcharts-figure">
<div id="container"></div>
<p class="highcharts-description">
</p>
</figure>
我添加了一个将 p(百分比)添加到数据的代码,我还想知道 hightcharts 是否已经这样做了。
解决方案
您可以通过将多个数据标签定义为数组来将它们添加到单个点:
dataLabels: [{
...
}, {
...
}]
现场演示:http: //jsfiddle.net/BlackLabel/5gL6paqr/
API 参考: https ://api.highcharts.com/highcharts/series.column.dataLabels
推荐阅读
- python-3.x - 无法在 kivy 窗口中显示 arduino 数据
- javascript - 如何在laravel中找到给定城市的给定地址?
- terraform - Terraform 上中间值的本地值和 null_data_source 之间的差异
- reactjs - 如何使用 React Hooks 和直接使用 DOM 的对象构建组件?(例如 OpenLayers)?)
- javascript - 有什么方法可以自动播放带有角度的 chrome 音频的视频
- reporting-services - 为什么 ssrs 报告订阅处于待处理状态并且交付很晚
- angular - 路由器使用角度 7 导航
- spring-boot - JPA - 当两个外键是实体的主键时,OneToOne 关系出现问题
- node.js - 如何将每个乘以作为快速车把(#each)?
- gradle - Gradle 和 webpack --watch