【问题标题】:Hide labels from pie chart in chartjs在chartjs中隐藏饼图中的标签
【发布时间】:2021-05-17 19:30:57
【问题描述】:

我想从饼图顶部删除标签。但不是来自鼠标悬停。如果我评论当我将鼠标悬停在图表上时显示未定义的标签选项,我该如何实现这一点

var ctx = $("#doughnutChart").get(0).getContext('2d');
new Chart(ctx, {
   type: 'pie',
   data: { // I want to hide this labels.
     labels: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'],
     datasets: [{
       label: 'User',
       backgroundColor: colors,
       data: usersData
     }]
   },
   options: {
     responsive: true,
   }
});

【问题讨论】:

    标签: chart.js


    【解决方案1】:

    您可以在选项中将图例设置为display: false,如下所示:

    V2:

      options: {
        legend: {
          display: false
        }
      }
    

    V3:

      options: {
        plugins: {
          legend: {
            display: false
          }
        }
      }
    

    V2 示例:

    var options = {
      type: 'pie',
      data: {
        labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
        datasets: [{
          label: '# of Votes',
          data: [12, 19, 3, 5, 2, 3],
          borderWidth: 1
        }]
      },
      options: {
        legend: {
          display: false
        }
      }
    }
    
    var ctx = document.getElementById('chartJSContainer').getContext('2d');
    new Chart(ctx, options);
    <body>
      <canvas id="chartJSContainer" width="600" height="400"></canvas>
      <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.4/Chart.js"></script>
    </body>

    V3 示例:

    var options = {
      type: 'pie',
      data: {
        labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
        datasets: [{
          label: '# of Votes',
          data: [12, 19, 3, 5, 2, 3],
          borderWidth: 1
        }]
      },
      options: {
        plugins: {
          legend: {
            display: false
          }
        }
      }
    }
    
    var ctx = document.getElementById('chartJSContainer').getContext('2d');
    new Chart(ctx, options);
    <body>
      <canvas id="chartJSContainer" width="600" height="400"></canvas>
      <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.2.0/chart.js"></script>
    </body>

    【讨论】: