【问题标题】:Is there a way in chartjs to display different Boolean values with an offset in Y over a common timeline?chartjs 中是否有一种方法可以在公共时间线上显示不同的布尔值和 Y 中的偏移量?
【发布时间】:2024-01-03 08:35:01
【问题描述】:

我目前有一个显示多个数据的散点图。 现在我想显示和比较布尔值。这些都是重叠的,不能很好地分析。

当前代表:Chart with Boolean values

是否可以缩小 Y 轴并在 Y 轴的 y 方向设置偏移量?

或者是否有可能将不同的图表堆叠在一起,并将上方的 X 轴与最低图表的 X 轴相关联?

目标是这样的表示: https://react.rocks/example/react-d3-boolean-chart

【问题讨论】:

  • 您可以将布尔值转换为数字并使用自定义轴和工具提示标签,以便显示您的布尔值。需要一些工作,但会工作。对于一段时间内的布尔值,我个人使用here 之类的时间线图,使用fanthos' timeline chart

标签: html charts chart.js scatter


【解决方案1】:

您可以通过移动各个数据集的 y 值来做到这一点。例如,如果您有 3 个数据集,则生成的值如下:

数据集 1: false:-0.1 / true:0.9
数据集 2: false:0 / true:1
数据集 3: 假:0.1 / 真:1.1

请看下面的可运行代码sn-p。

var chart = new Chart('myChart', {
  type: 'line',
  data: {
    datasets: [{
      label: 'A',
      data: [
          { x: "2020-06-07 08:51:22", y: -0.1 },
          { x: "2020-06-07 09:22:01", y: 0.9 },
          { x: "2020-06-07 09:37:28", y: -0.1 },
          { x: "2020-06-07 10:10:51", y: 0.9 },
          { x: "2020-06-07 11:42:54", y: 0.9 }
      ],
      borderColor: 'green',
      fill: false,
      steppedLine: 'before'
    },
    {
      label: 'B',
      data: [
          { x: "2020-06-07 08:45:17", y: 0 },
          { x: "2020-06-07 09:30:17", y: 1 },
          { x: "2020-06-07 10:15:16", y: 0 },
          { x: "2020-06-07 11:00:17", y: 1 },
          { x: "2020-06-07 12:15:16", y: 0 }
      ],
      borderColor: 'red',
      fill: false,
      steppedLine: 'before'
    },
    {
      label: 'C',
      data: [
          { x: "2020-06-07 09:00:28", y: 1.1 },
          { x: "2020-06-07 09:15:44", y: 0.1 },
          { x: "2020-06-07 10:41:05", y: 1.1 },
          { x: "2020-06-07 11:22:18", y: 0.1 },
          { x: "2020-06-07 12:33:54", y: 1.1 }
      ],
      borderColor: 'blue',
      fill: false,
      steppedLine: 'before'
    }]
  },
  options: {
    tooltips: {
      callbacks: {
        label: tooltipItem => tooltipItem.value < 0.5 ? 'false' : 'true'
      }
    },
    scales: {
      xAxes: [{
        type: 'time',
        time: {
          unit: 'minute',
          displayFormats: {
            minute: 'HH:mm'            
          },
          tooltipFormat: 'HH:mm'
        },
        ticks: {
          source: 'data',
          minRotation: 45
        },
        gridLines: {
          drawOnChartArea: false
        }
      }],
      yAxes: [{
        ticks: {
          min: -0.3,
          max: 1.3,
          fontSize: 16,
          fontStyle: 'bold',
          callback: value => {
            if (value == 0) {
              return 'off';
            } else {
              return value == 1 ? 'on' : '';
            }
          }  
        },
        gridLines: {
          display: false
        }
      }]
    }
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.bundle.min.js"></script>
<canvas id="myChart" height="70"></canvas>

【讨论】:

    最近更新 更多