How to display second y-axis to right of grouped b

2019-07-27 03:44发布

问题:

I am creating a grouped bar chart with d3 using the following example as my starting point. I've made a couple of minor modifications for readability as displayed in the screenshot below; the screenshot also demonstrates the issue I'm encountering.

I want to add a second y-axis but naturally I want it to be all the way over to the right. As you can see from the screenshot though it is to the right of the left-oriented y-axis but also adjacent to it instead of to the right of the data.

What I did to get where I am is to add the following (note orient("right"))

var yRight = d3.svg.axis()
    .scale(y)
    .orient("right");

Then I applied the following append, even at the very end of the Javascript source code in case order matters, but to no avail. I based both things on how the (left) yAxis was being handled, but clearly there is something further that needs doing in order to move the second y axis all the way to the right of the actual chart.

svg.append("g")
    .attr("class", "y axis")
    .call(yRight);

回答1:

Based on this other example I found my answer, and that was to add a transform/translate clause as follows:

svg.append("g")
    .attr("class", "y axis")
    .attr("transform", "translate(" + width + " ,0)")
    .call(yRight);

I'm completely new to d3 though so some explanation of what transform/translate do from d3 experts in the comments would definitely improve the quality of this Q&A.



回答2:

Yes, as you found, .orient adjust the axis label positions, not the axis itself: "Changing the orientation affects the position of the ticks and their labels in relation to the axis path, but does not change the position of the axis itself; to change the position of the axis with respect to the plot, specify a transform attribute on the containing g element." mbostock wiki

The "transform", "translate" shifts all points by the X and Y values. This is an SVG command, not D3. So, your command

 .attr("transform", "translate(" + width + " ,0)")

moved the 2nd y-axis to the right by "width" pixels, like you wanted. Notice that you had already done the same thing with you x-axis:

svg.append("g")
.attr("class", "x axis")
.attr("transform", "translate(0," + height + ")")
.call(xAxis);

You used transform to shift it down by "height" pixels. Without this translate, the x-axis would be along the top of the chart.

There are other useful transforms, like rotate, which can be used to rotate the axis labels. Useful when they are long and start overlapping each other. SVG doc transform