[Chartjs]-Legend not displaying on Line or Bar chart – React-Chartjs-2

2πŸ‘

βœ…

It looks like the defaults can’t handle being passed an object, if you define the defaults for the legend label padding and boxWidth separately then it will render your legend.

Normal example but problem was the same as if you would use react wrapper:

const defaults = Chart.defaults;

defaults.global.elements.point.radius = 1;
defaults.global.elements.line.tension = 0.1;
defaults.global.elements.point.hoverRadius = 10;
defaults.global.elements.point.hitRadius = 12;

// Font
defaults.global.defaultFontSize = 12;
defaults.global.defaultFontColor = "#838383";

// Legend
defaults.global.legend.display = true;
defaults.global.legend.align = "start";
defaults.global.legend.position = "bottom";
defaults.global.legend.labels.padding = 30;
defaults.global.legend.labels.boxWidth = 15;

var options = {
  type: 'line',
  data: {
    labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
    datasets: [
        {
          label: '# of Votes',
          data: [12, 19, 3, 5, 2, 3],
        borderWidth: 1
        },  
            {
                label: '# of Points',
                data: [7, 11, 5, 8, 3, 7],
                borderWidth: 1
            }
        ]
  },
  options: {
    scales: {
        yAxes: [{
        ticks: {
                    reverse: false
        }
      }]
    }
  }
}

var ctx = document.getElementById('chartJSContainer').getContext('2d');
new Chart(ctx, options);
canvas { 
 background-color : #eee;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.4/Chart.js" integrity="sha512-hZf9Qhp3rlDJBvAKvmiG+goaaKRZA6LKUO35oK6EsM0/kjPK32Yw7URqrq3Q+Nvbbt8Usss+IekL7CRn83dYmw==" crossorigin="anonymous"></script>
<body>
    <canvas id="chartJSContainer" width="600" height="400"></canvas>
</body>

2πŸ‘

Already answer has been given even though, I would like to give alternative solution without defaults namespace options.

We can achieve it with plugins namespace in reactjs.

 <Line
      data={{
        labels: ["1", "2", "3", "4", "5", "6"],
        datasets: [
          {
            label: "Primary kVA",
            data: [6, 17, 12, 19, 10, 55, 5, 22, 3, 100, 200, 350],
            fill: false,
            backgroundColor: "rgb(255, 99, 132)",
            borderColor: "rgba(255, 99, 132, 0.2)",
          },
          {
            label: "Redundant kVA",
            data: [12, 23, 33, 55, 22, 300, 100, 200, 350],
            fill: false,
            backgroundColor: "rgb(77, 255, 156)",
            borderColor: "rgb(77, 255, 156,0.73)",
          },
        ],
      }}
      options={{
        plugins: {
          legend: {
            display: true,
            position: "right",
            align: "start",
            labels: {
              usePointStyle: true,
            },
          },
        },
      }}
    />

Leave a comment