chart.js-每条水平线 [英] chart.js - Horizontal lines per bar

查看:64
本文介绍了chart.js-每条水平线的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用chart.js 2.9.2绘制每条带有2个数据集(实际,目标)的水平线的图表,如下所示:

I am trying to draw a chart with horizontal line per bar with 2 datasets(Actual,Target) using chart.js 2.9.2, like this:

但没有成功...这有可能吗?

but with no success... is that possible?

推荐答案

您可以将目标值转换为浮动条,其中使用语法 [min,max] 指定单个条。给定名为 targetData 的值数组,可以使用 Array.map() 如下。

You can convert your target values into floating bars where individual bars are specified with the syntax [min, max]. Given an array of values named targetData, it can be converted with Array.map() as follows.

targetData.map(v => [v - 1, v + 1])

此外,您需要为两个数据集定义单个堆叠的 xAxis 。为了在工具提示中显示原始目标值,请使用 toolips.callback.label 函数也是必需的。

Further you need to define individual stacked xAxis for both datasets. In order to have the original target values displayed in the tooltips, a toolips.callback.label function is also needed.

请查看下面的可运行代码段。

Please have a look at below runnable code snippet.

const actualData = [100, 180, 120, 80, 140, 170, 160];
const targetData = [110, 150, 140, 100, 120, 110, 170];

new Chart("chart", {
  type: "bar",
  data: {
    labels: ["KPI 1", "KPI 2", "KPI 3", "KPI 4", "KPI 5", "KPI 6", "KPI 7"],
    datasets: [{
        label: "Actual",
        backgroundColor: 'rgba(0, 0, 255, 0.2)',
        data: actualData,
        xAxisID: "x-axis-actual"
      },
      {
        label: "Target",
        backgroundColor: 'rgba(255, 0, 128, 1)',
        data: targetData.map(v => [v - 1, v + 1]),
        xAxisID: "x-axis-target"
      }
    ]
  },
  options: {
    tooltips: {
      callbacks: {
        label: (tooltipItem, data) => {
          const v = data.datasets[tooltipItem.datasetIndex].data[tooltipItem.index];
          return Array.isArray(v) ? (v[1] + v[0]) / 2 : v;
        }
      }
    },
    scales: {
      xAxes: [{
          id: "x-axis-target",
          stacked: true
        },
        {
          display: false,
          offset: true,
          stacked: true,
          id: "x-axis-actual",
          gridLines: {
            offsetGridLines: true
          }
        }
      ],
      yAxes: [{
        ticks: {
          beginAtZero: true
        }
      }]
    }
  }
});

<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.min.js"></script>
<canvas id="chart" height="120"></canvas>

这篇关于chart.js-每条水平线的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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