reverse how vertical bar chart is drawn

若如初见. 提交于 2021-02-05 07:04:50

问题


How can I reverse how my vertical bar is drawn? I want it to be drawn from the bottom to the top. It is important to maintain the right representation of the dataset

https://jsfiddle.net/adai183/ztsh1ptx/

var dataset = [ 10, 80, 5, 5];

//Create SVG element
var svg = d3.select("body")
    .append("svg")
    .attr("width", w)
    .attr("height", h);

svg.selectAll("rect")
    .data(dataset)
    .enter()
    .append("rect")
    .attr("fill", "rgb(250, 128, 114)")
    .attr("x", function(d, i) {
        return i * (w / dataset.length);
    })
    .attr("y", function(d) {
        return h - (d * 4);
    })
    .attr("width", w / dataset.length - barPadding)
    .attr("height", 0)
    .transition().duration(750).ease("linear")
    .attr("height", function(d) {
        return d * 4;
});

回答1:


Do it like this:

    .attr("y",  function(d) {
        return h; //set y to max height
    })
    .attr("width", w / dataset.length - barPadding)
    .attr("height", 0)//height of the bars initially is 0
    .transition().duration(750).ease("linear")//on transition
    .attr("y",  function(d) {
        return d*4;//set the y to its value
    })
    .attr("height", function(d) {
        return h - (d * 4);//set the height to max height - y's value
})

working code here

EDIT

For solving that problem make a scale for y:

var y = d3.scale.linear()
    .range([h, 0])
        .domain([0,100]);//since values vary between 0 and 100

Now use this scale to give height to your bar chart.

.transition().duration(750).ease("linear")
    .attr("y",  function(d) {
        return y(d);
    })
    .attr("height", function(d) {
        return h - y(d);
})

working example here

Hope this helps!



来源:https://stackoverflow.com/questions/35311893/reverse-how-vertical-bar-chart-is-drawn

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