简体   繁体   中英

How to always show a label in ChartJS in React

I'm trying to have my data points on a line graph to always show a value. Like this:

在此处输入图像描述

I've found a solution that works on ChartJS vanilla, but can't figure out how to use ChartJS with React (using functional components preferably).

So far I've got a simple chart working as follows:

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>
    )
}

Does anyone know where to go from here?

I was having trouble to have the labels show up with 2.0.0 version of plugin and v3 of react-chartjs-2 until I found that we need to explicit registration of plugin in someway (specific charts or global) since version v1 of the plugin.

https://v2_0_0--chartjs-plugin-datalabels.netlify.app/guide/getting-started.html#integration

Registration: Since version 1.x, this plugin no longer registers itself automatically. It must be manually registered either globally or locally

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: {
    // ...
  }
})

OK, so in the absence of figuring out how to use the vanilla method in the above, I found that the datalabels plugin is a really handy tool to achieve this.

All you have to do is run npm install chartjs-plugin-datalabels --save

Then add to your component.js file: import 'chartjs-plugin-datalabels';

And that's all you need to get this: 在此处输入图像描述

There's a great example on codesandbox that I found that demonstrates how to change the label content and formatting. It's for a bar chart - but I didn't find it difficult to transfer the code to my line chart.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM