如何始终在 React 的 ChartJS 中显示标签
How to always show a label in ChartJS in React
我试图让我的数据点在线图上始终显示一个值。像这样:
我发现了一个 适用于 ChartJS vanilla,但无法弄清楚如何将 ChartJS 与 React 一起使用(最好使用功能组件)。
到目前为止,我得到了一个简单的图表,如下所示:
import React from 'react'
import { Line } from 'react-chartjs-2'
const dataForGraph = () => {
return {
labels: ["January", "February", "March", "April", "May", "June", "July"],
datasets: [{
label: "My First dataset",
data: [65, 59, 80, 81, 56, 55, 40]
}]
}
}
export default function LineChart() {
const data = (canvas) => {
const ctx = canvas.getContext("2d")
return dataForGraph()
}
var options = {
}
return (
<Line
data={data}
options={options}
>
</Line>
)
}
有人知道从这里到哪里去吗?
好的,在没有弄清楚如何使用上面的普通方法的情况下,我发现 datalabels plugin 是一个非常方便的工具来实现这一点。
你所要做的就是运行
npm install chartjs-plugin-datalabels --save
然后添加到你的组件.js文件:
import 'chartjs-plugin-datalabels';
这就是您需要的全部内容:
我在 codesandbox 上找到了一个很好的示例,它演示了如何更改标签内容和格式。它用于条形图 - 但我发现将代码转移到我的折线图并不困难。
我在使用 2.0.0 版本的插件和 v3 的 react-chartjs-2 显示标签时遇到了麻烦,直到我发现我们需要以某种方式(特定图表或全局)显式注册插件,因为插件的 v1 版本。
https://v2_0_0--chartjs-plugin-datalabels.netlify.app/guide/getting-started.html#integration
报名:
自版本 1.x 起,此插件不再自动注册。必须在全局或本地手动注册
import ChartDataLabels from 'chartjs-plugin-datalabels';
// Register the plugin to all charts:
Chart.register(ChartDataLabels);
// OR only to specific charts:
var chart = new Chart(ctx, {
plugins: [ChartDataLabels],
options: {
// ...
}
})
我试图让我的数据点在线图上始终显示一个值。像这样:
我发现了一个
到目前为止,我得到了一个简单的图表,如下所示:
import React from 'react'
import { Line } from 'react-chartjs-2'
const dataForGraph = () => {
return {
labels: ["January", "February", "March", "April", "May", "June", "July"],
datasets: [{
label: "My First dataset",
data: [65, 59, 80, 81, 56, 55, 40]
}]
}
}
export default function LineChart() {
const data = (canvas) => {
const ctx = canvas.getContext("2d")
return dataForGraph()
}
var options = {
}
return (
<Line
data={data}
options={options}
>
</Line>
)
}
有人知道从这里到哪里去吗?
好的,在没有弄清楚如何使用上面的普通方法的情况下,我发现 datalabels plugin 是一个非常方便的工具来实现这一点。
你所要做的就是运行
npm install chartjs-plugin-datalabels --save
然后添加到你的组件.js文件:
import 'chartjs-plugin-datalabels';
这就是您需要的全部内容:
我在 codesandbox 上找到了一个很好的示例,它演示了如何更改标签内容和格式。它用于条形图 - 但我发现将代码转移到我的折线图并不困难。
我在使用 2.0.0 版本的插件和 v3 的 react-chartjs-2 显示标签时遇到了麻烦,直到我发现我们需要以某种方式(特定图表或全局)显式注册插件,因为插件的 v1 版本。
https://v2_0_0--chartjs-plugin-datalabels.netlify.app/guide/getting-started.html#integration
报名: 自版本 1.x 起,此插件不再自动注册。必须在全局或本地手动注册
import ChartDataLabels from 'chartjs-plugin-datalabels';
// Register the plugin to all charts:
Chart.register(ChartDataLabels);
// OR only to specific charts:
var chart = new Chart(ctx, {
plugins: [ChartDataLabels],
options: {
// ...
}
})