javascript - 如何使用 chart.js 在条形图中沿水平线绘制多个颜色条
问题描述
我正在 react 环境中使用 chart.js 制作图表。
如果你看第二张图,如果水平线有 130% 怎么办?100
形成gray
100 及以上green
。我也想以与上述相同的格式制作它。
找了2天,不知道怎么弄
这是我正在进行的工作。
我想以这种格式制作。
这是我的代码。
import { Bar, Chart } from 'react-chartjs-2';
import annotationPlugin from "chartjs-plugin-annotation";
import "chartjs-plugin-datalabels";
import ChartDataLabels from "chartjs-plugin-datalabels";
Chart.register([annotationPlugin], [ChartDataLabels] );
let chartColors = {
yellow: '#F4D068',
green: '#4CC26F',
gray: '#EBEBEB'
};
const data = {
labels: ['January', 'February', 'March', 'April', 'May', 'June'],
datasets: [
{
label: 'My First dataset',
backgroundColor: [],
borderColor: '#EBEBEB',
borderWidth: 1,
borderRadius: 10,
data: [65, 140, 130, 200, 56, 35, 80],
random: ['Check', 'Out', 'Udemy', 'Course', 'Charjs 3', 'Coming Out', 'Next week'],
},
],
};
let colorChangeValue = 100;
let dataset = data.datasets[0];
for (let i = 0; i < dataset.data.length; i++) {
if (dataset.data[i] > colorChangeValue) {
dataset.backgroundColor[i] = chartColors.green;
if (dataset.data[i] < 100) {
dataset.backgroundColor[i] = chartColors.gray;
}
}
if (dataset.data[i] < colorChangeValue) {
dataset.backgroundColor[i] = chartColors.yellow;
}
}
return (
<Bar
data={data}
width={100}
height={70}
options={{
scales: {
x: {
stacked: true,
grid: {
display: false,
},
},
y: {
stacked: true,
grid: {
},
ticks: {
maxTicksLimit: 1
}
}
},
plugins: {
legend: {
display: false
},
title: {
display: true,
text: "범례1",
padding: {
bottom: 30
},
weight: "bold",
color: "#00325c",
font: {
size: 13
},
align: "start"
},
datalabels: {
display: true,
color: "black",
anchor: 'end',
align: 'top',
formatter: function (value) {
return "\n" + value + "%";
}
}
},
annotations: {
myHorizontalLine: {
type: "line",
scaleID: "y",
borderWidth: 3,
borderColor: "#333333",
value: 100,
borderDash: [8, 8],
label: {
font: {
weight: "normal"
},
rotation: "auto",
enabled: true
}
},
}
}}
/>
)
解决方案
您可以定义第二个数据集,它只将灰色空间绘制到 100 的限制。
{
backgroundColor: '#DDD',
hoverBackgroundColor: '#DDD',
data: [100, 0, 0, 0, 100, 100],
datalabels: {
display: false
}
},
还要确保只有 x 轴有选项stacked: true
。
除此之外,您还需要调整一些其他选项。例如tooltip.filter
,将阻止 Chart.js 显示第二个数据集的工具提示。
tooltip: {
filter: tooltipItem => !tooltipItem.datasetIndex
},
请用您修改的代码查看StackBlitz ,看看它是如何工作的。
推荐阅读
- html - 其他页面看不到布局页面
- python-3.x - Odoo:在创建时在另一个模型的 many2one 字段中保存当前 ID
- angular - 无法解析Angular中类的所有参数
- uwp - UWP 中的图像下降被相关面板包围
- firebase - 旧版 GCE 和 GKE 元数据服务器端点和 Firebase 函数
- python - 如何将凌乱的 csv 文件清理并构建成 pandas 数据框
- javascript - 如何使用户上传的图片自动调整到我的 PHP 网站上的特定宽度和高度而不破坏尺寸?
- c# - smtp.gmail.com - 无法从网站工作 - Hostgator 服务器
- kentico - Kentico 11 - 管理员门户样式损坏
- javascript - 如何在javascript中更改数组的数据?