Chartjs-Ionic: Doughnut Chart's legend occupies complete card in mobile, while on big screen chart and legend looks fine

0👍

You can put the legend at the bottom, after which you can play with the aspectRatio property to get the exact view that you’re aiming for…

to toggle between desktop and mobile views… we use the onResize method… where we shift the position of the legend from right to bottom as we move to a smaller size…

relevant HTML

<ion-card>
  <ion-card-header>
    Capacity Distribution
  </ion-card-header>
  <ion-card-content>
    <canvas #lineChart>{{ chart }}</canvas>
  </ion-card-content>
</ion-card>

relevant TS

this.chart = new Chart(this.chartRef.nativeElement, {
      type: 'doughnut',
      data: {
        labels: ['Rage 30 TB', 'Free 15 TB', 'Dead 12 TB', 'Slce 10 TB', 'Phtion 10 TB', 'Chehead 8 TB',
          'Logion 8 TB', 'Usaity 4 TB', 'Dirhead 3 TB'],
        datasets: [{
          // label: '# of Votes',
          data: [30, 15, 12, 10, 10, 8, 8, 4, 3],
          backgroundColor: [
            'rgba(255, 159, 64, 0.8)',
            'rgba(255, 99, 132, 0.8)',
            'rgba(54, 162, 235, 0.8)',
            'rgba(255, 206, 86, 0.8)',
            'rgba(75, 192, 192, 0.8)',
            'rgba(229, 0, 255, 0.8)',
            'rgba(0, 255, 127, 0.8)',
            'rgba(255, 233, 0, 0.8)',
            'rgba(0, 182, 255, 0.8)',

          ],
          // hoverBackgroundColor: [
          //   '#FFCE56',
          //   '#FF6384',
          //   '#36A2EB',
          //   '#FFCE56',
          //   '#FF6384'
          // ]
        }]
      },
      options: {
        responsive: true,
        aspectRatio: 1,
        maintainaApectRatio: true,
        onResize: function () {
          if (window.innerWidth > 700) {
            this.legend.position = 'right';
            this.legend.aspectRatio = 1.4;
            this.legend.maintainaApectRatio = false;
          } else {
            this.legend.position = 'bottom';
            this.legend.aspectRatio = 1;
            this.legend.maintainaApectRatio = true;
          }
        },
        legend: {
          display: true,
          position: "bottom",
          labels: {
            // fontFamily: "Comic Sans MS",
            // boxWidth: 2,
            // boxHeight: 2
          }
        }
      }
    });

complete working stackblitz here

Leave a comment