简体   繁体   中英

ChartJs Scatter with Bars

I need to use Vertical Bars in a Scatter chart, but although there is no error, the bars never appears.

new Chart(ctx, 
{
    type: 'scatter',
    labels: xAxisValues,
    data: 
    {
        datasets:
        [
            {
                type: 'bar',
                label: 'Label nº A',
                backgroundColor: '#000',
                borderWidth: 2,
                fill: false,
                data: barValues,
                yAxisID: 'A'
            },
            {
                type: 'line',
                label: 'Label nº B',
                backgroundColor: '#cc99ff',
                data: lineValues,
                yAxisID: 'B',
                pointRadius: 0,
            }
        ]
    }
});

As you can see in this JSFiddle , If I switch from bar to line it works. It seems to me that the bars cannot receive the properties xy which I'm passing as follows:

var barValues = 
[
    {x: 393, y: 1},
    {x: 401, y: 2},
    {x: 409, y: 7},
    {x: 417, y: 4},
    {x: 425, y: 0},
    {x: 433, y: 3},
    {x: 441, y: 2},
    {x: 449, y: 1},
    {x: 457, y: 0}
];

But how do I then have a bar in a scatter chart?

Within a vertical bar chart, individual bars get evenly spread among the available space on the x-axis. Therefore, in order to be in sync with the line chart, the bar chart data array should have the same number of entries. Except for the few bar positions, all these values will be zero. This can be obtained with the following function that is used when the bar data is created.

function barValue(x) {
    for (let barValue of barValues) {
    if (Math.floor(x) == barValue.x) {
      return barValue.y;
    }
  }
  return 0;
}
...

data: lineValues.map(v => barValue(v.x)),

Please have a look at this Fiddle that illustrates how the problem can be solved.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM