javascript - 无需单击即可访问chartJs中特定条形的yLabel
问题描述
我正在研究应根据 yLabel 中的值确定条形背景颜色的 chartJs。
我们如何访问chartjs中特定条形的yLabel进行比较?
const waterFChart = new Chart(canvasRef.current, {
plugins: [ChartDataLabels],
type: "bar",
data: {
labels: ["Label 1", "Label 2", "Label 3", "Label 4", "Label 5"],
datasets: [
{
label: 'Failures',
type: "bar",
data: [10, 20, 30, 41, 51],
//background color is assigned based on if yLabel of bar matches testValue
backgroundColor: ylabel === testvalue ? "red" : "yellow",
//how can we access yLabelhere
hoverBackgroundColor: darkBar,
stack: 'Stack 1',
}
}
);
解决方案
您可以像这样使用可编写脚本的选项:
const yVal = 12;
const primeCrolor = "green";
const secondColor = "red"
const options = {
type: 'bar',
data: {
labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
datasets: [{
label: '# of Votes',
data: [12, 19, 3, 5, 2, 3],
backgroundColor: (ctx) => {
if (!ctx.parsed) {
return secondColor
}
const allTicks = ctx.chart.scales.y.ticks.map(e => e.value);
return (allTicks.includes(yVal) && ctx.parsed.y === yVal) ? primeCrolor : secondColor;
}
}]
},
options: {
// Scale config only needed for example to force the correct labels
scales: {
y: {
min: 0,
max: 20,
ticks: {
stepSize: 2
}
}
}
}
}
const 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.5.1/chart.js"></script>
</body>
推荐阅读
- c++ - 查找给定序列是单调的还是严格单调的
- python - Python 自动化,关注 Chrome 浏览器,获取 URL
- c# - “没有给出与所需形式参数相对应的参数
- python - 正在运行无效的条件语句
- react-native - 使用颤振制作群组语音通话应用程序(如不和谐)
- php - php 从 textarea 读取的每一行都不起作用,为什么?
- jquery - Aframe 中用于定位的动画不起作用
- laravel - Vue 没有安装在 Laravel 中
- python - 指数移动平均线 df.ewm() 函数
- c# - 如何在 CosmosSDK v3+ 的 FeedResponse 中提供模拟值?