隐藏数据标签chart.js并使用粗线绘制/标记y = 0

gxwragnw  于 2023-10-18  发布在  Chart.js
关注(0)|答案(1)|浏览(156)

如何隐藏顶部的数据标签,并绘制一条线性线(在背景中)y = 0,颜色不同于数据集(用红色水平线显示)
我还想画第二条dotted水平线来表示平均水平(例如。y = 2.4

new Chart(canvas_id, {
    type: 'line',
    data: {
        datasets: [{
            data: dates,
            borderWidth: 2
        }],
        //labels: ['a', 'b']
    },
    options: {
        responsive: true,
        maintainAspectRatio: false,
        elements: {
            point: {
                radius: 0
            }
        },
        plugins: {
            tooltip: {
                enabled: false
            }
        }
    }
});

zpjtge22

zpjtge221#

对于第一个问题,您必须禁用图例:

plugins: {
   // ..... other plugins options
   legend: {
     display: false
   }
}

对于第二个问题,您可以使用chartjs-plugin-annotation
在加载插件后,例如从CDN加载插件(根据您如何包含它,您还必须注册插件-对于CDN脚本来说不必要),您可以定义这样的行:

plugins: {
      // .... other plugin options
      annotation: {
        annotations: {
          line1: {
            type: 'line',
            yMin: 2.4,
            yMax: 2.4,
            borderColor: 'rgb(255, 99, 132)',
            borderWidth: 2,
          }
        }
      }
    }

片段:

const dates = Array.from({
    length: 16
  },
  (_, i) => ({
    x: '' + (Math.floor(new Date().valueOf() / 1000) + 24 * 3600 * i),
    y: 50 * Math.exp(-(i - 8) * (i - 8)) - Math.random() * 20
  }))

new Chart('chart1', {
  type: 'line',
  data: {
    datasets: [{
      data: dates,
      borderWidth: 2
    }],
    //labels: ['a', 'b']
  },
  options: {
    responsive: true,
    maintainAspectRatio: false,
    elements: {
      point: {
        radius: 0
      }
    },
    plugins: {
      tooltip: {
        enabled: false
      },
      legend: {
        display: false
      },
      annotation: {
        annotations: {
          line1: {
            type: 'line',
            yMin: 2.4,
            yMax: 2.4,
            borderColor: 'rgb(255, 99, 132)',
            borderWidth: 2,
          }
        }
      }
    }
  }
});
<div style="min-height: 300px">
    <canvas id="chart1">
    </canvas>
  </div>
  
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/4.4.0/chart.umd.js" integrity="sha512-6HrPqAvK+lZElIZ4mZ64fyxIBTsaX5zAFZg2V/2WT+iKPrFzTzvx6QAsLW2OaLwobhMYBog/+bvmIEEGXi0p1w==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>

<script src="https://cdnjs.cloudflare.com/ajax/libs/chartjs-plugin-annotation/3.0.1/chartjs-plugin-annotation.min.js" integrity="sha512-Hn1w6YiiFw6p6S2lXv6yKeqTk0PLVzeCwWY9n32beuPjQ5HLcvz5l2QsP+KilEr1ws37rCTw3bZpvfvVIeTh0Q==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>

or fiddle
当然,如果没有这个插件,您也可以在第一个数据集的x区间两端定义两个点作为第二个数据集,并将所需值定义为y--jsFiddle

相关问题