【问题标题】:Set fix values on y-axis vue-chartjs在 y 轴 vue-chartjs 上设置固定值
【发布时间】:2017-07-13 04:13:16
【问题描述】:

我使用vue-chartjs 作为chartjs 的包装器。我有一个带有随机数据的简单折线图,但坚持如何设置要在图表的 y 轴上显示的固定值。目前我有0-100的随机数据。现在,我想要实现的只是在y轴上显示0, 50, 100,无论随机值是从0-100开始。

示例脚本

putData: function () {
    this.datacollection = {
        labels: ['JAN', 'FEB', 'MAR', 'APR', 'MAY', 'JUN', 'JUL', 'AUG', 'SEP', 'OCT', 'NOV', 'DEC'],
        datasets: [{
            lineTension: 0,
            borderWidth: 1,
            borderColor: '#F2A727',
            pointBackgroundColor:[ '#fff', '#fff', '#fff', '#fff', '#fff', '#F2A727'],
            backgroundColor: 'transparent',
            data: [this.getRandomInt(), this.getRandomInt(), this.getRandomInt(), this.getRandomInt(), this.getRandomInt(), this.getRandomInt()]
        }]
    }
},

getRandomInt: function () {
    return Math.floor(Math.random() * (95)) + 5
}

任何帮助将不胜感激。

【问题讨论】:

    标签: chart.js vue-chartjs


    【解决方案1】:

    为此,您需要在图表选项中为 y 轴刻度设置 stepSize: 50maxTicksLimit: 3

    scales: {
       yAxes: [{
          ticks: {
             stepSize: 50,
             maxTicksLimit: 3
          }
       }]
    }
    

    【讨论】:

      【解决方案2】:

      以上答案是正确的。 对于那些感兴趣的人,我发布了最新版本 Chart.js 的代码

      更新到 Chart.js v3.2.0(不向后兼容 v2.xx

      如果您的随机数据值都在接近 50 的中间范围内,为了避免自动缩放,请执行以下操作:

      添加 min: 0max: 100 ,因此您可以强制图表准确显示这 3 个刻度,包括 0,因此 maxTicksLimit: 3:

      100

      50

      0

      <script>
         // ...
      
      options: {
         scales: {
            y: {
               min: 0,
               max: 150,
               ticks: {
                  stepSize: 50,
                  maxTicksLimit: 3
               }
            }
         }
      };
      
         // ...
      </script>
      

      来源:https://www.chartjs.org/docs/latest/axes/#tick-configuration

      (请注意,在新版本 v3.xx 中,min: 0max: 100 现在位于 外部 刻度对象,而在 v2. xx 它曾经在刻度对象内)。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2015-11-02
        • 1970-01-01
        • 2013-09-30
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-11-24
        相关资源
        最近更新 更多