简体   繁体   中英

Line chart legend border style using react-chartjs-2

Is it possible to make the legend box of dashed line in line chart to have no dashed border?

I read about generateLegend() and legendCallback but I can't understand how it works in react-chartjs-2 together with React functional component. Also, I'm not sure if they can be used to change the border style of legend.

This is my sample code:

import { Line } from "react-chartjs-2";

const LineChart = () => {
    const data = {
        labels: ["Jan", "Feb", "Mar", "Apr", "May", "Jun"],
        datasets: [
            {
                label: "Line 1", data: [10, 10, 20, 20, 30, 30]
            },
            {
                label: 'Line 2',
                borderDash: [15, 5],
                data: [20, 20, 20, 20, 20, 20],
            }],
    };

    const options = {
        legend: {
            position: legendPosition,
            align: legendAlign,
        }
    };

    return <Line data={data} options={options} />
};

This is sample of desired Line 1(red) and Line 2(grey dahsed)在此处输入图像描述

You have to use borderWidth:0 so, please remove borderDash: [15, 5] and add borderWidth: 0, . Or you can completely replace data with below:

const data = {
    labels: ["Jan", "Feb", "Mar", "Apr", "May", "Jun"],
    datasets: [
        {
            borderWidth: 0,
            label: "Line 1", data: [10, 10, 20, 20, 30, 30]
        },
        {
            label: 'Line 2',
            borderWidth: 0,
            data: [20, 20, 20, 20, 20, 20],
        }],
};

Update

You have to use borderWidth: 0 in data.datasets and this is mandatory for you requirement. Moreover, you can pass options={options} into Line to have more configuration for legend like legend background-color or legend font-color or legend boxWidth and so on.

Here is the Code Sandbox

Here is the output picture

在此处输入图像描述

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