javascript - 图表 js 2 个条形图,顶部有一个自定义标签
问题描述
我有几个像 A 和 B 这样的值,现在我有一对我在 chart-js 上显示它们,就像这样
现在对于我的用例,我使用 A 和 BEg a=100 和 b=50 计算第三个值,除以它们将得到 c=2.0。现在我想在 A 和 B 栏上显示这个 c 值作为一个像这样的公共标签
"chart.js": "^3.3.0",
react-js
const newChartInstance = new Chart(chartContainer.current, {
type: "bar",
options: {
scales: {
yAxes: [
{
ticks: {
beginAtZero: true,
},
},
],
},
...config.options,
onClick: (e) => {
const points = newChartInstance.getElementsAtEventForMode(
e,
"nearest",
{ intersect: true },
true
);
if (points.length) {
const firstPoint = points[0];
var type =
newChartInstance.data.datasets[firstPoint.datasetIndex].label;
var label = newChartInstance.data.labels[firstPoint.index];
var value =
newChartInstance.data.datasets[firstPoint.datasetIndex].data[
firstPoint.index
];
// This is the result that you will use to breakdown the chart
//console.log(label, value, type);
dispatch(setClickedBar({ label, value, type, tile: props.tile }));
}
},
},
data: data,
});
解决方案
您可以为此使用自定义插件:
var options = {
type: 'bar',
data: {
labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
datasets: [{
label: '# of Votes',
data: [12, 19, 3, 5, 2, 3],
backgroundColor: 'red'
},
{
label: '# of Points',
data: [7, 11, 5, 8, 3, 7],
backgroundColor: 'blue'
}
]
},
options: {
plugins: {
customValue: {
name: 'ROI',
}
}
},
plugins: [{
id: 'customValue',
afterDraw: (chart, args, opts) => {
const {
ctx,
data: {
datasets
},
_metasets
} = chart;
datasets[0].data.forEach((dp, i) => {
let barValue = `${(datasets[1].data[i] + dp) / 2}%`;
const lineHeight = ctx.measureText('M').width;
const textVal = opts.name || 'fill'
ctx.textAlign = 'center';
ctx.fillText(barValue, _metasets[0].data[i].x, (_metasets[0].data[i].y - lineHeight * 1.5), _metasets[0].data[i].width);
ctx.fillText(textVal, _metasets[0].data[i].x, (_metasets[0].data[i].y - lineHeight * 3), _metasets[0].data[i].width);
});
}
}]
}
var ctx = document.getElementById('chartJSContainer').getContext('2d');
new Chart(ctx, options);
<body>
<canvas id="chartJSContainer" width="600" height="400"></canvas>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.4.1/chart.js"></script>
</body>
推荐阅读
- jenkins - 由于标签格式错误,Jenkins master 无法在 k8s 上启动 slave
- modelica - Modelica 中的解码器有什么问题?
- jquery - 当分辨率低于一定数量的像素时更改分割顺序
- javascript - 接收来自多个帐户的消息
- .net - 如何在 c# 中的 Registry.CurrentUser.OpenSubKey 中设置以管理员身份运行?
- php - PHP-Ajax:带有下拉菜单的实时搜索并在点击时赋值
- twig - 有条件地渲染带有回退的 twig 变量
- python - 为什么 Python 在从 Pandas 系列中提取时似乎忽略了通配符?
- python - 优化 pandas 数据帧适用于解码 CAN 帧 - 遍历行
- r - 为什么在 R 中使用 pagedown 制作的 html cv 的 Google chrome 打印会在页面中留下空白?