How to set the domain and scale on an yaxis on a discreteBarChart nvd3.js

强颜欢笑 提交于 2019-12-30 18:48:08

问题


I'm using d3.js charts in one of my applications. Here they are in this image See Charts

For Y axis on Money chart (See in the Image), I want maximum value rounded to 400, no matter what maximum bar size is here it is $358.72, but I want to keep bar at 358.72 but on Y Axis it would be 400 Limit.

Code for it is here

tradesChart = [ 
      {
        key: "Cumulative Return",
        values: [
                        {
            "label" : "6E",
            "value" : 100       },
                    {
            "label" : "NG",
            "value" : 100       },
                    {
            "label" : "TF",
            "value" : 67        }        ]
      }
    ];
        nv.addGraph(function() {

      var chart = nv.models.discreteBarChart()
          .x(function(d) { return d.label })
          .y(function(d) { return d.value/100 })
          .staggerLabels(true)
          .showValues(true)
          .valueFormat(d3.format('.0%'))

      chart.yAxis.tickFormat(function(d) { return d3.format('d')(d*100) + '%'; });

      d3.select('#chart-trades svg')
        .datum(tradesChart)
        .transition().duration(500)
        .call(chart);

      nv.utils.windowResize(chart.update);

      return chart;
    });

Kindly Help me to solve this out


回答1:


You need to modify the domain of the Y-axis scale. Usually it is derived from the maximum value of the data with a statement like the following:

yScale.domain([0, d3.max(data, function (d) { return d.v; }) ]);

In your case, you should modify it to be more like this instead:

yScale.domain([0, 400]);

Alternatively, if you want to set the maximum value from the data or a minimum static value, you could do something like the following:

yScale.domain([0, d3.max(data, function (d) { return d.v > 400 ? d.v : 400; }) ]);

A full example jsfiddle is here.

That's how to do it with D3.js, I'm not familiar with the venerable nvd3.js lib, so I'm not sure how to access the scale, but i'll take a look and see if I can find it.




回答2:


Force Y

List of numbers to Force into the Y scale (ie. 0, or a max / min, etc.). The numbers tell the d3.js the values to use in the scale, rather than d3.js determining the values.

Datatype: Array of Numbers (i.e. [0, 50]

http://cmaurer.github.io/angularjs-nvd3-directives/line.chart.html




回答3:


I use nvd3 and for me this worked instead:

nv.models.discreteBarChart().yDomain([0,400])

I could'nt get it to work with yScale.domain



来源:https://stackoverflow.com/questions/14840759/how-to-set-the-domain-and-scale-on-an-yaxis-on-a-discretebarchart-nvd3-js

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!