简体   繁体   English

如何在 D3 v6 中调整条形图的 y 轴比例?

[英]How to adjust the scale in the y-axis for a bar chart in D3 v6?

I am trying to create a bar chart right now, but currently I am facing a problem that my bars are not properly scaled comparing to the data.我现在正在尝试创建一个条形图,但目前我面临一个问题,即我的条形与数据相比没有正确缩放。 Here is my code in D3:这是我在 D3 中的代码:



var third_width = 1000;
var third_height = 450;
var third_padding = 30;
    
var third_countries = ["Australia", "Austria", "Denmark", "Netherlands","New Zealand", "Norway", "Sweden", "UK","USA","Japan","Poland","Finland","Italy","France","Belgium"]
var third_data = [102, 39, 81, 50, 61, 79, 81, 77, 59, 64, 56, 65, 57, 85, 50];

var third_xScale = d3.scaleBand()
                     .domain(d3.range(third_data.length))
                     .rangeRound([third_padding ,third_width])
                     .paddingInner(0.1);

var third_yScale = d3.scaleLinear()
                     .domain([0, d3.max(third_data)])
                     .range([third_height - third_padding, third_padding]);

var third_xAxis = d3.axisBottom()
                    .scale(third_xScale).tickFormat(function(i) {return third_countries[i];})

var third_yAxis = d3.axisLeft()
                    .scale(third_yScale).ticks(5);

var third_svg = d3.select("#chart3")
                  .append("svg")
                  .attr("width", third_width)
                  .attr("height", third_height);

third_svg.selectAll("rect")
    .data(third_data)
    .enter()
    .append("rect")
    .attr("x", function(d, i) {
       return third_xScale(i);
    })
    .attr("y", function(d) {
       return third_height - third_padding - third_yScale(d);
    })
    .attr("width", third_xScale.bandwidth())
    .attr("height", function(d) {
       return third_yScale(d);
    })
    .attr("fill", function(d) {
       return "rgb(0, 0, " + Math.round(d * 10) + ")";
    });

//Create "Food waste per capita (kg/year)" on Y Axis
third_svg.append('text')
        .attr('x', 5)
        .attr('y', 20)
        .attr('text-anchor', 'left')
        .style('font-family', 'Helvetica')
        .style('font-size', 'small')
        .text('Food waste per capita (kg/year)');

third_svg.append("g")
         .attr("class", "axis")
         .attr("transform", "translate(" + third_padding + ",0)")
         .call(third_yAxis);



third_svg.append("g")
         .attr("class", "axis")
         .attr("transform", "translate(0,"+ (third_height - third_padding) + ")")
         .call(third_xAxis);

And you could see the result on this image, in which the first bar indicates a value of nearly 10 rather than 102:您可以在这张图片上看到结果,其中第一条表示接近 10 而不是 102 的值: 结果 D3 代码

Could you please help me to know how to fix the axes in this case, so that the value in y-axis could be lined up?您能帮我知道在这种情况下如何固定轴,以便排列 y 轴中的值吗?

Thank you!谢谢!

The direction of your Y scale (downside-up) is opposite to the SVG's (upside-down). Y 刻度的方向(倒置)与 SVG 的方向(倒置)相反。

It can be solved by switching the values of y and height attributes for the <rect> s:可以通过切换<rect>yheight属性的值来解决:

third_svg.selectAll("rect")
  .data(third_data)
  .enter()
  .append("rect")
  .attr('y', d => third_yScale(d))
  .attr("height", d => third_height - third_padding - third_yScale(d))
  ...

See it's working in the snippet:查看它在代码段中的工作:

 const third_width = 1000; const third_height = 450; const third_padding = 30; const third_countries = ["Australia", "Austria", "Denmark", "Netherlands","New Zealand", "Norway", "Sweden", "UK","USA","Japan","Poland","Finland","Italy","France","Belgium"] const third_data = [102, 39, 81, 50, 61, 79, 81, 77, 59, 64, 56, 65, 57, 85, 50]; const third_xScale = d3.scaleBand().domain(d3.range(third_data.length)).rangeRound([third_padding,third_width]).paddingInner(0.1); const third_yScale = d3.scaleLinear().domain([0, d3.max(third_data)]).range([third_height - third_padding, third_padding]); const third_xAxis = d3.axisBottom().scale(third_xScale).tickFormat(function(i) {return third_countries[i];}) const third_yAxis = d3.axisLeft().scale(third_yScale).ticks(5); const third_svg = d3.select("#chart3").append("svg").attr("width", third_width).attr("height", third_height); third_svg.selectAll("rect").data(third_data).enter().append("rect").attr("x", (d, i) => third_xScale(i)).attr('y', d => third_yScale(d)).attr("height", d => third_height - third_padding - third_yScale(d)).attr("width", third_xScale.bandwidth()).attr("fill", d => `rgb(0, 0, ${d * 2})`); //Create "Food waste per capita (kg/year)" on Y Axis third_svg.append('text').attr('x', 5).attr('y', 20).attr('text-anchor', 'left').style('font-family', 'Helvetica').style('font-size', 'small').text('Food waste per capita (kg/year)'); third_svg.append("g").attr("class", "axis").attr("transform", "translate(" + third_padding + ",0)").call(third_yAxis); third_svg.append("g").attr("class", "axis").attr("transform", "translate(0,"+ (third_height - third_padding) + ")").call(third_xAxis);
 <script src="https://cdnjs.cloudflare.com/ajax/libs/d3/6.7.0/d3.min.js"></script> <div id="chart3" />

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

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