首页 > 解决方案 > 隐藏 Chart.js 中的所有标签和工具提示并使其非常小

问题描述

所以我试图在我的反应应用程序中使用 react-chartjs-2 创建一些简约图表。

我想要实现的是,在我创建的小卡片内有一个非常小的图表,没有任何类型的标签。我想隐藏标签、图例,甚至图表网格。

在我看过的文档或其他堆栈溢出问题中,我找不到如何使它像这样工作。

结果应该类似于: 期望的结果

现在的样子

先感谢您。

标签: javascriptreactjschart.jsreact-chartjs

解决方案


您可以简单地更新options属性,例如:

options: {
    tooltips: {
      enabled: false,
    },
    legend: {
      display: false
    },
    scales: {
      xAxes: [{display: false}],
      yAxes: [{display: false}],
    }
  }

为了使其非常小,您可以将画布放在容器 div 中,例如:

<div class="chart-container">
    <canvas id="myChart"></canvas>
</div>

并添加一些 CSS,例如:

.chart-container {
   width: 200px;
}
#myChart {
  display: block; 
  width: 200px; 
  height: 50px;
}

您可以根据您的要求在此处更新width& 。height

工作演示:

var ctx = document.getElementById('myChart').getContext('2d');
var chart = new Chart(ctx, {
  // The type of chart we want to create
  type: 'line',

  // The data for our dataset
  data: {
    labels: ['January', 'February', 'March', 'April', 'May', 'June', 'July'],
    datasets: [{
      label: 'My First dataset',
      backgroundColor: 'rgb(255, 99, 132)',
      borderColor: 'rgb(255, 99, 132)',
      data: [0, 10, 5, 15, 20, 30, 45]
    }]
  },

  // Configuration options go here
  options: {
    tooltips: {
      enabled: false,
    },
    legend: {
      display: false
    },
    scales: {
      xAxes: [{
        display: false
      }],
      yAxes: [{
        display: false
      }],
    }
  }
});
.chart-container {
   width: 200px;
}
#myChart {
  display: block; 
  width: 200px; 
  height: 50px;
}
<script src="https://cdn.jsdelivr.net/npm/chart.js@2.8.0"></script>

<div class="chart-container">
    <canvas id="myChart"></canvas>
</div>


推荐阅读