Chart.js 图例占用太多空间

2022-01-22 00:00:00 legend javascript chart.js

我在使用 chart.js 图例时遇到了一些问题.长文本的图例占用了太多空间,导致我的饼图尺寸减小:

I was having some problem with chart.js legend. The legend with long text took up too much spaces which resulting in the reduce in the size of my pie chart:

另一个例子是这样的:

如果我得到更多的图例,圆环图最终会变得越来越小.

If I got more legend, the doughnut chart will eventually becomes smaller and smaller.

我尝试设置 maxWidth 但无济于事.

I tried to set maxWidth but to no avail.

var options = {
            layout: {
                padding: {
                  top: 5
                }
            },
            responsive: true,
            maintainAspectRatio: false,
            legend: {
                display: true,
                position: 'right',
                maxWidth: 100,
                onClick: null
            },
            animation: {
                animateScale: true,
                animateRotate: true
            },

        };

有什么想法吗?

我尝试按照这个 [解决方案][3] 创建一个 html 图例:

I tried to follow this [solution][3] to create a html legend:

<div class="box-body" style="height:350px;">
<div class="float-left">
<div class="float-left" style="width:70%">

<canvas id="brandChart" style="position: relative; height: 350px;"></canvas>
</div>
<div class="float-left" style="width:30%">

<div id="js-legend" class="chart-legend">
</div>

</div>
</div>

它确实限制了图例的宽度,但这导致了另一个问题,即在我折叠并展开 div 之后,画布丢失了,我只剩下图例 div.

It did restricted the width for legend, but then this lead to another problem which is after I collapsed and expanded the div, the canvas just went missing and I am only left with the legend div.

推荐答案

首先,使用它的原生属性设置画布的宽度和高度(做not 使用 style 属性),像这样:

First off, set canvas­'s width and height using it­'s native attributes (do not use style attribute), like so :

<canvas id="brandChart" width="700" height="350"></canvas>

注意:宽度应该是高度的两倍

note: width should be twice the height

然后,在图表选项中将 responsive 属性设置为 false,如下所示:

Then, set responsive property to false in your chart options, as such :

options: {
   responsive: false,
   ...
}

ᴅᴇᴍᴏ

var chart = new Chart(brandChart, {
   type: 'doughnut',
   data: {
      labels: ['Etronin Home Appliances Service & trading Pte Ltd', 'Giant'],
      datasets: [{
         data: [30, 70],
         backgroundColor: ['#2196f3', '#4caf50']
      }]
   },
   options: {
      responsive: false,
      legend: {
         display: true,
         position: 'right',
         onClick: null
      },
   }
});

<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.6.0/Chart.min.js"></script>
<canvas id="brandChart" width="700" height="350"></canvas>

相关文章