Vue Chart.js - 条形图上的简单 dot/line

Vue Chart.js - simple dot/line on bar chart

我需要在我的 bar 图表上添加一条简单的 dot/vertical 线,该线具有动态 X 值,0 代表 Y 值。我需要的预览(红点):

绿色值是动态的。

我的当前状态预览:

其中 3.30 应该是点的 X 坐标 - [3.30, 0].

我正在使用 Vue chart for the charts and I tried do create a mixed 一个与 barscatterscatter 需要 type: 'linear' 因为它是 xAxis bar 图表不适合我的需要。

所以我尝试使用 chartjs-plugin-annotation 并且它是接受 "coordinates" 的 box 类型但是这里的问题是 X 必须是X 轴上的固定值labels 对象)。如果我将 X 轴设为 [3,0],它会起作用,但如果有小数,例如 [3.5, 0],它不会起作用。


  // data
  options: {
    responsive: true,
    maintainAspectRatio: false,
    legend: {
      display: false
    },
    scales: {
      yAxes: [{
        ticks: {
          min: 0,
          max: 1,
          stepSize: 0.1
        }
      }]
    }
  }

  // computed 
  labels: [1, 2, 3, 4, 5, 6], // fixed value, there are always 6 bars
  datasets: [
    {
      label: 'Values',
      backgroundColor: '#f89098',
      data: this.tableInputValues // array of decimal values
    }
  ]

所以,我的问题是如何在 Chart.js 条形图上放置 "simple" 点或垂直线,其中点有X 轴的动态值 -> [动态值,0]。

仅供参考 - 关于 Expected value

据我所知,Vue Chart 使用 canvas(如 Demo page 中所见)。
因此,我的建议是在 DOM 中检索代表图表的 canvas 节点并动态写入所需的点。例如:

var c = document.getElementById("bar-chart");   //hereby assuming canvas named "bar-chart"
var ctx = c.getContext("2d");
ctx.fillStyle = "#ff0000";                     //red color for the dot
ctx.beginPath();
let yPosition = c.height - 5;                 //fixed y position
let xPosition = 35;                          //that's the dynamic expected value
ctx.arc(xPosition, yPosition, 2.5, 0, 2 * Math.PI);
ctx.fill();

Here 你找到了一个展示如何使用 Vue 实现的演示。在这种情况下,您需要包装代码以在 afterDraw 挂钩中的 canvas 上绘制一个点。这个钩子需要作为插件附加到图表组件,所以像这样:

...
mounted () { 
   //adding the plugin to draw the red dot
   this.addPlugin({
    id: 'chart-plugin',
    afterDraw: function (chart) {
       var c = chart.canvas;   
       var ctx = c.getContext("2d");
       ctx.fillStyle = "#ff0000";                     
       ctx.beginPath();
       let xPosition = 742; //x positioning to be calculated according to your needs
       let yPosition = c.height - 28;                                       
       ctx.arc(xPosition, yPosition, 3, 0, 2 * Math.PI);
       ctx.fill();
    }
  });

  //actual chart rendering
  this.renderChart({ 
    ...
  });
}
...

为了完整起见,here 您找到 Chart.js 插件 API.

所有可用挂钩的列表

这是我针对你的问题的解决方案https://jsfiddle.net/huynhsamha/e54djwxp/

这是结果的截图

在我的解决方案中,我使用 type="line",x 轴和 y 轴都使用 type="linear"。我还将 属性 options 添加到 <chart> 以便在 ChartJS

中使用 options
<div id="vue">
  <chart type="line" :data="data" :options="options"></chart>
</div>

options 将设置 x 轴和 y 轴以呈现数据点和预期值:

      options: {
        scales: {
            xAxes: [{
            type: 'linear',
            ticks: {
                min: 1,
                max: 6,
                stepSize: 1
            }
          }],
           yAxes: [{
            type: 'linear',
            ticks: {
                min: 0,
                max: 1,
                stepSize: 0.1
            }
            }]
        }
      }

data 将有 2 个 datasets。第一个是数据点,使用类型 line,第二个是期望值,使用类型 bubble.

      data: {
        datasets: [{
            label: 'Frequency Data',
            data: dataPoints.map(({ val, freq }) => ({
                x: val,
              y: freq
            })),
            backgroundColor: 'rgba(72, 202, 59, 0.4)',
            borderColor: 'rgba(72, 202, 59, 1)'
        }, {
            label: 'Expected Value',
            type: 'bubble',
            data: [{ 
                x: expectedValue, 
              y: 0, 
              r: 8 // radius
            }],
            backgroundColor: 'rgba(255, 68, 0, 0.4)',
            borderColor: 'rgba(255, 68, 0, 1)'
        }]
        },

datasets 中,我们有 dataPointsexpectedValue,它将从 API 中获取以获取您的数据点。我还为数据点模拟了简单的 API:

// simulate the API to get data points
const retrieveData = () => [
    { val: 1, freq: 0.15 },
    { val: 2, freq: 0.25 },
    { val: 3, freq: 0.3 },
    { val: 4, freq: 0.2 },
    { val: 5, freq: 0.1 },
    { val: 6, freq: 0.45 }
]


// fetch your data here, return array of JSON { val, freg }
const dataPoints = retrieveData() || [];

// calculate expected value = sum( val * freq ) each i in dataPoints
const expectedValue = dataPoints.reduce((cur, { val, freq }) => cur + val * freq, 0).toFixed(4);

您可以 运行 片段或 运行 fiddle https://jsfiddle.net/huynhsamha/e54djwxp/92/

<script async src="//jsfiddle.net/huynhsamha/e54djwxp/92/embed/js,html,css,result/dark/"></script>