简体   繁体   English

如何在堆叠的d3条形图中添加正确缩放的y轴

[英]How to add a properly scaled y axis to a stacked d3 bar chart

I've been working with Mike Bostock's stacked bar chart (here: https://bl.ocks.org/mbostock/4679202 ). 我一直在使用Mike Bostock的堆积条形图(在这里: https : //bl.ocks.org/mbostock/4679202 )。

I've successfully made a number of modifications, but what I'm stuck on is trying to add ay axis with ticks and properly scaled values. 我已经成功进行了许多修改,但我遇到的问题是尝试添加带有刻度和适当缩放值的y轴。

I thought it would simply be done by using this: 我认为只需使用以下命令即可完成:

var yAxisRight = d3.svg.axis().scale(y2) //define ticks
    .orient("right").ticks(5); 

However, that results in the values for only ONE set of the stack being used for the entire Y axis. 但是,这导致整个Y轴仅使用一组堆栈的值。 This results in an incorrect scale. 这会导致比例尺错误。 The values for the range of all stacks COMBINED needs to be used to determine the range of values I believe. 我相信所有合并的堆栈范围的值都需要用来确定值的范围。

Is there an easy way to do this that I'm missing? 有没有一种简单的方法可以实现我所缺少的功能? To sum the range of all the columns. 汇总所有列的范围。

If not, how would I write a function to set the range based on the values in all 4 columns? 如果没有,我将如何编写一个函数来基于所有4列中的值设置范围?

Here is a working JSfiddle of what I have now (which is incorrect): https://jsfiddle.net/1jhm7ths/ 这是我现在所拥有的工作的JSfiddle(这是不正确的): https ://jsfiddle.net/1jhm7ths/

If I understood correctly what you tried to achieve, you need to compute your range based on your stacked data and not the original ones. 如果我正确理解您要达到的目标,则需要根据堆叠数据而不是原始数据来计算范围。 I updated your jsFiddle with the following modification on line 92: 我在第92行进行了以下修改来更新您的jsFiddle

y2.domain([0, d3.max(dataByGroup, function(d) { return d3.sum(d.values, function(v) {return v.value;}); })]); //added

What this does is taking each group, computing the sum of all values, and the taking the max of the sums. 这样做是取每个组,计算所有值的总和,然后取总和的最大值。

On a side note, I would discourage learning d3 v3 and try to focus on the v4 for longer term support, latest functionalities, modulariy, and a ton of other advantages. 附带一提,我不鼓励学习d3 v3,并尝试将重点放在v4上以获得长期支持,最新功能,模块化以及大量其他优势。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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