Praveen
Praveen

Reputation: 347

Issue with rectangles not drawing equal with yaxis labels in d3v4

I am new to d3v4 and working on a chart where i need to show little rectangle on certain date matching to its title on yaxis. The problem i am facing is rectangles in the chart area not drawing equal to the yaxis point labels, i have tried changing the y value by hardcoding, it works fine but the point is the number of data object will change in real time like it could be any number of objects in an array. Here is the plunker

To draw the graph dynamically with limited data objects i've created few buttons on top of chart so that rectangles in the chart can draw equal to y-axis labels.

Any help is much appreciated.

Upvotes: 0

Views: 23

Answers (1)

Gerardo Furtado
Gerardo Furtado

Reputation: 102174

You are using a band scale: that being the case, you should not change the y position, which should be just...

.attr('y', function(d) {
    return yScale(d.title);
})

.. and you should not hardcode the height: use the bandwidth() instead:

.attr('height', yScale.bandwidth())

The issue now is setting the paddingInner and paddingOuter of the scale until you have the desired result. For instance:

var yScale = d3.scaleBand().domain(data.map(function(d) {
        return d.title
    }))
    .range([height - 20, 0])
    .paddingInner(0.75)
    .paddingOuter(.2);

Here is the plunker with those changes: https://plnkr.co/edit/ZxGCeDGYwDGzUCYiSztQ?p=preview

However, if you still want (for whatever reason) hardcode the height or the width of the rectangles, use a point scale instead, and move the y position by half the height.

Upvotes: 1

Related Questions