简体   繁体   English

如何缩放条形图的条形图,以便显示带有数据的完整图形

[英]How to scale bars of barchart so it shows the complete graph with data

I created a simple barchart with d3.js. 我用d3.js创建了一个简单的条形图。 My problem my complete chart is not shown but it is cut off to the right. 我的问题是我的完整图表未显示,但在右侧被切断。 Only 16 of the 20 bars are shown 仅显示20条中的16条

I guess it is a scaling issue but I don't know how to fix it. 我想这是一个扩展问题,但我不知道如何解决。 If I increase the width it shows me more bars, but I'd like to keep the original width. 如果我增加宽度,它会显示更多条,但我想保留原始宽度。 Here is my code: 这是我的代码:

{#Creating a barchart#}
var dataset = [133,131,111,345,665,665,454,44,4,235....]; //These are the bars

var svgWidth = 900, svgHeight = 400, barPadding = 10;
var barWidth = (svgWidth / dataset.length * 2 );

var svg = d3.select('svg')
    .attr("width", svgWidth)
    .attr("height", svgHeight);

var yScale = d3.scaleLinear()
    .domain([0, d3.max(dataset)])
    .range([0, svgHeight]);

var barChart = svg.selectAll("rect")
    .data(dataset)
    .enter()
    .append("rect")
    .attr("y", function(d) {
         return svgHeight - yScale(d)
    })
    .attr("height", function(d) {
        return yScale(d);
    })
    .attr("width", barWidth - barPadding)
    .attr("transform", function (d, i) {
        var translate = [barWidth * i, 0];
        return "translate("+ translate +")";
    });

var text = svg.selectAll("text")
    .data(dataset)
    .enter()
    .append("text")
    .text(function(d) {
        return d;
    })
    .attr("y", function(d, i) {
        return svgHeight - d - 2;
    })
    .attr("x", function(d, i) {
        return barWidth * i;
    })
    .attr("fill", "black");

</script>

Any help is highly appreciated!! 任何帮助都非常感谢! Thanks in advance! 提前致谢!

尝试在barWidth公式中删除乘以2

var barWidth = svgWidth / dataset.length;

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

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