React-chartjs-2: How to display values on react-chartjs-2

Created on 26 Dec 2016  路  5Comments  路  Source: reactchartjs/react-chartjs-2

like this

image

Most helpful comment

Here's a little workaround that worked for me. You just have to dig really dip into the chart instance. First you need to get the chart instance as described here: https://github.com/gor181/react-chartjs-2#chartjs-instance
And then in componentDidMount:
````
...
componentDidMount() {
Chart.pluginService.register({
afterDraw: () => {
let ctx = this.refs.chart.chart_instance.chart.ctx;
ctx.font = "12px Verdana";
ctx.fillStyle = "#000000";
ctx.textAlign = "center";
ctx.textBaseline = "bottom";

            this.refs.chart.chart_instance.chart.config.data.datasets.forEach(function (dataset) {
                if(dataset.type === 'bar'){
                    const dataArray = dataset.data;
                    dataset._meta[0].data.forEach(function (bar, index) {
                        ctx.fillText(dataArray[index], bar._view.x, bar._view.y);
                    });
                };
            })
        }
    });
}

...
````
I was creating a combined line + bars graph, so I had to check the dataset type. You might not need it.

screen shot 2017-01-25 at 15 08 09

All 5 comments

Here's a little workaround that worked for me. You just have to dig really dip into the chart instance. First you need to get the chart instance as described here: https://github.com/gor181/react-chartjs-2#chartjs-instance
And then in componentDidMount:
````
...
componentDidMount() {
Chart.pluginService.register({
afterDraw: () => {
let ctx = this.refs.chart.chart_instance.chart.ctx;
ctx.font = "12px Verdana";
ctx.fillStyle = "#000000";
ctx.textAlign = "center";
ctx.textBaseline = "bottom";

            this.refs.chart.chart_instance.chart.config.data.datasets.forEach(function (dataset) {
                if(dataset.type === 'bar'){
                    const dataArray = dataset.data;
                    dataset._meta[0].data.forEach(function (bar, index) {
                        ctx.fillText(dataArray[index], bar._view.x, bar._view.y);
                    });
                };
            })
        }
    });
}

...
````
I was creating a combined line + bars graph, so I had to check the dataset type. You might not need it.

screen shot 2017-01-25 at 15 08 09

unable to access chart instance with latest update. Is there any working example for this?

this.refs.chart.chart_instance.chart.ctx; not working.

You can also use a plugin, chartjs-plugin-datalabels

@naresh25ganji Try this.refs.chart.chartInstance.chart.ctx

Closing for now. Please refer to the Chart.js documentation for questions around configuration and/or usage of the library. If you have a bug or enhancement related directly to Chart.js, please open an issue on their Github.

Was this page helpful?
0 / 5 - 0 ratings