Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
490 views
in Technique[技术] by (71.8m points)

javascript - Dis Alignment of bar chart in D3.js

I am trying to render Bar chart with D3.js but facing the following alignment issue :

enter image description here

actually the data that I am trying to render is :

0: {year: "2011", count: 5462}
1: {year: "2012", count: 4984}
2: {year: "2013", count: 4980}
3: {year: "2014", count: 5244}
4: {year: "2015", count: 5181}
5: {year: "2016", count: 5084}
6: {year: "2017", count: 5354}
7: {year: "2018", count: 5927}
8: {year: "2019", count: 5659}

The code that I used to render the above chart is :

function render(data)
{   
const width = 400;
const height = 300;
const margin = {
    'top' : 100,
    'left' : 100,
    'right' : 100,
    'bottom' : 100
};
const svg = d3.select('svg');
const chartContainer = svg.append('g')
    .attr('transform', `translate(${margin.left}, ${margin.top})`)
    .attr('class', 'holder');

const chart = chartContainer.select('g')
    .data(data)
    .enter();

const xScale = d3.scaleBand()
    .range([0, width])
    .domain(data.map(obj => obj.year));

const yScale = d3.scaleLinear()
    .range([height, 0])
    .domain([0,d3.max(data, d => d.count) + 100]);

chartContainer.append('g')
    .call(d3.axisLeft(yScale));

chartContainer.append('g')
    .attr('transform', `translate(0, ${height})`)
    .call(d3.axisBottom(xScale));


chart.select('.holder')
.append('rect')
    .attr('x', (d) => xScale(d.year))
    .attr('y', (d) => yScale(d.count))
    .attr('width', xScale.bandwidth())
    .attr('height', (d) => height - yScale(d.count))

 }

Any kind of help is appreciated, Thanks in advance :)

question from:https://stackoverflow.com/questions/65913576/dis-alignment-of-bar-chart-in-d3-js

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

Please log in or register to answer this question.

Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...