简体   繁体   中英

Bars are going beyond the chart range in d3 bar chart

Bars in the grouped bar chart positioned correctly across x axis, however even thought I have a pre-defined range some of the bars are always beyond the chart with some y value equals to eg enormous -31199600.

CodeSandbox

// chart dimensions
const height = 600;
const colorScale = d3.scaleOrdinal().range(['#4FD8DD']);
const itemWidth = 140;
const barWidth = 3;
const barMargin = 5;
const xMargin = 80;
const yMargin = 150;

 const svg = svgEl
      .append('g')
      .attr('class', 'grouped-bar-chart')
      .attr('width', storeData.dataset.length * itemWidth + xMargin * 2)
      .attr('height', height);

    const xScale = d3
      .scaleBand()
      .domain(storeData.dataset.map((d) => d.city))
      .range([0, storeData.dataset.length * itemWidth]);

    const yScale = d3.scaleLinear().range([-120, height - 200]);

    yScale.domain([d3.max(storeData.dataset[0].values, (d) => d.value), 0]);

    // draw chart
    svg
      .selectAll('g.city')
      .data(storeData.dataset, (d) => d.city)
      .enter()
      .append('g')
      .classed('city', true)
      .attr(
        'transform',
        (d) =>
          `translate(${xMargin + xScale(d.city) + itemWidth / 2},${yMargin})`
      )
      .each(function (d) {
        const city = d3.select(this);
        for (let i = 0; i < d.values.length; i++) {
          const y = yScale(d.values[i].value);
          console.log(
            'yScale(d.values[i].value) --->',
            yScale(d.values[i].value)
          );
          console.log('yScale(0) --->', yScale(0));
          const height = yScale(0) - y;
          const x = (i - d.values.length / 2) * (barWidth + barMargin);
          city
            .append('rect')
            .attr('x', x)
            .attr('y', y)
            .attr('width', barWidth)
            .attr('height', height)
            .style('fill', colorScale(i));
        }
      });

This code sets 5000 as the max value:

const maxValue = d3.max(storeData.dataset[0].values, (d) => d.value);
yScale.domain([maxValue, 0]);

Actually, max value is much higher (I get 400000000):

const maxValue = storeData.dataset.reduce((maxAll, item) => {
  return item.values.reduce((maxItem, val) => 
    Math.max(maxItem, val.value), maxAll);
}, 0);
    
console.log('MAX VALUE: ', maxValue);

Setting a correct value as domain upper limit for the yScale should solve the issue.

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