如何在ChartsJS中换行标签对象(嵌套数组将不起作用) [英] How to line break a label object in ChartsJS (nested arrays won't work)

查看:282
本文介绍了如何在ChartsJS中换行标签对象(嵌套数组将不起作用)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

正如在这里回答的那样,我使用嵌套数组在ChartsJS上对标签进行换行,并且效果很好,但如果尝试在标签(数据集内的对象)上使用嵌套数组,则它们不会换行.

As answered here I'm using nested arrays to line break my labels on ChartsJS and it works fine but if I try to use nested arrays on my label (the object inside dataset) they won't line break.

例如此图:

我有2个带有新行的标签,但是如果我对标签使用相同的技术(图形上方的图例),则不会换行.

I have 2 labels with new lines but if I try the same technique with my label (the legend above the graph) it won't line break.

以下是此图的代码:

data: {  labels: [ 'Utensilios para escrita e artes','Faz de conta','Jogos',['Materiais não estruturado','/de largo alcançe/recicláveis'],['Repertório artístico-cultural e','científico de diferentes','origens étnico-raciais'],'Livros de história','Materiais para pesquisa',],

            datasets: [
                    { maxBarThickness: 70,label: 'Não há material presente',
                    backgroundColor: '#eb7071',

                    borderWidth: 1,
                    data: [ 2,41,24,51,78,33,62,]
                    }, 
                    { maxBarThickness: 70,label: ['Material presente,',' mas crianças não usaram'],
                    backgroundColor: '#f9ae60',

                    borderWidth: 1,
                    data: [ 24,38,48,39,15,48,30,]
                    }, 
                    { maxBarThickness: 70,label: 'Crianças usaram os materiais',
                    backgroundColor: '#73e599',

                    borderWidth: 1,
                    data: [ 73,21,28,10,7,20,7,]
                    }, 

                ]
            },

我认为图例不会换行,因为在代码中它不是嵌套数组,因此我将标签更改为:

I assumed the legend would not line break because in the code it was not a nested array so I changed my label to this:

label: [['Material presente,',' mas crianças não usaram']]

但是它仍然没有用.

是否有任何方法可以使这些图例换行,而不必将其生成为HTML脚本来对其进行操作?

Is there any way to line break these legends without having to generate them as a HTML script to manipulate them?

推荐答案

没有可以定义的选项来轻松实现您想要的目标.自2016年以来,针对该选项就存在一个开放的功能请求.

There's no option that can be defined to easily achieve what you're looking for. An open feature request exists for such an option since 2016.

您必须生成自定义 HTML图例使用legendCallback.

You'll have to generate custom HTML legend using legendCallback.

受此答案的启发,我想到了以下代码,说明了如何在您的情况下完成此操作.进一步改善图例标签的样式并使其适应您的需求应该不难.

Inspired by this answer, I came up with the following code that illustrates how this can be done in your case. It shouldn't be too hard to further improve the styling of the legend labels and adapted them to your needs.

const chart = new Chart(document.getElementById("chart"), {
  type: "bar",
  data: {
    labels: [
      ['Utensilios para', 'escrita e artes'],
      ['Materiais não estruturado', 'de largo alcançe/recicláveis'],
      ['Repertório artístico-cultural e', 'científico de diferentes', 'origens étnico-raciais']
    ],
    datasets: [{
        label: "Não há material presente",
        data: [5, 8, 4],
        fill: false,
        backgroundColor: "rgba(255, 99, 132, 0.2)",
        borderColor: "rgb(255, 99, 132)",
        borderWidth: 1
      },
      {
        label: ["Material presente", "mas crianças não usaram"],
        data: [3, 5, 4],
        fill: false,
        backgroundColor: "rgba(255, 159, 64, 0.2)",
        borderColor: "rgb(255, 159, 64)",
        borderWidth: 1
      },
      {
        label: "Crianças usaram os materiais",
        data: [6, 5, 7],
        fill: false,
        backgroundColor: "rgba(255, 205, 86, 0.2)",
        borderColor: "rgb(255, 205, 86)",
        borderWidth: 1
      }
    ]
  },
  options: {
    legend: {
      display: false
    },
    tooltips: {
      callbacks: {        
        title: (tooltipItems, data) => data.labels[tooltipItems[0].index],
        label: (tooltipItems, data) =>
          data.datasets[tooltipItems.datasetIndex].label + ': ' + tooltipItems.value + '%'
      }
    },
    legendCallback: chart => {
      let html = '<ul class="' + chart.id + '-legend">';
      chart.data.datasets.forEach((ds, i) => {
        html += '<li><span id="legend-' + i + '-item" style="background-color:' + ds.backgroundColor + '" onclick="updateDataset(event, \'' + i + '\')">';
        html += Array.isArray(ds.label) ? ds.label.join('<br />') : ds.label;
        html += '</span></li>';
      });
      return html + '</ul>';
    },
    scales: {
      yAxes: [{
        ticks: {
          beginAtZero: true
        }
      }]
    }
  }
});

$("#legend").html(chart.generateLegend());

// Show/hide chart by click legend
updateDataset = (e, dsIndex) => {
  let hide = !chart.data.datasets[dsIndex].hidden;
  chart.data.datasets[dsIndex].hidden = hide;
  if (hide) {
    $('#' + e.path[0].id).css("text-decoration", "line-through");
  } else {
    $('#' + e.path[0].id).css("text-decoration", "");
  }
  chart.update();
};

#legend>ul {
  padding: 0;
  text-align: center;
}

#legend li {
  cursor: pointer;
  margin: 10px 10px;
  display: inline-table;
}

#legend li span {
  position: relative;
  padding: 3px 5px;
  z-index: 2;
  font-family: Arial, Helvetica, sans-serif;
  font-size: 12px;
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.min.js"></script>
<div>
  <div id="legend"></div>
  <canvas id="chart"></canvas>
</div>

更新

与此同时,我回答了类似的问题,并花了一些时间来正确定义图例标签的样式.请查看此答案.

Meanwhile I answered a similar question and invested some time to properly define the styling of the legend labels. Please have a look at this anwser.

这篇关于如何在ChartsJS中换行标签对象(嵌套数组将不起作用)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆