【问题标题】:How can I make a bar chart starting from the 0 point of the y axis and not from the bottom of the svg?如何从 y 轴的 0 点开始而不是从 svg 的底部开始制作条形图?
【发布时间】:2023-03-23 07:19:02
【问题描述】:

我正在尝试制作条形图,但我想不出一种方法使条形图从 y 轴的 0 点开始,而不是从 svg 的最底部开始。我该如何解决?

 let url = "https://raw.githubusercontent.com/freeCodeCamp/ProjectReferenceData/master/GDP-data.json";

const padding = 50;
const height = 460;
const width = 900;

 var svg = d3.select('body')
    .append('svg')
    .attr('width', width)
    .attr('height', height);

var arr = [];
    d3.json(url, function(data) {
        for (let i = 0; i < data.data.length; i++) arr[i] = data.data[i]; 

    const yScale = d3.scaleLinear()
                     .domain([0, d3.max(arr, (d) => d[1])])
                     .range([height - padding, padding]);

    const yAxis = d3.axisLeft(yScale);

   svg.append('g')
      .attr('transform', 'translate(' + padding + ', 0)')
      .call(yAxis)

    svg.selectAll('rect')
        .data(arr)
        .enter()
        .append('rect')
        .attr('fill', 'blue')
        .attr('height', d => d[1] + padding)
        .attr('width', 2.909090909090909)
        .attr('x', (d, i) => padding + (3.2 * i))
        .attr('y', d => yScale(d[1]))
        .append('title')
        .text(d => d[1])

    });
    &lt;script src="https://d3js.org/d3.v4.min.js"&gt;&lt;/script&gt;

【问题讨论】:

    标签: javascript json svg d3.js bar-chart


    【解决方案1】:

    您错误地计算了矩形的高度,并且没有使用您的比例。这也比较棘手,因为您使用 padding 不是典型的 D3 约定。

        svg.selectAll('rect')
            .data(arr)
            .enter()
            .append('rect')
            .attr('fill', 'blue')
            .attr('height', d => height - padding - yScale(d[1]))
    

    【讨论】:

    • 那个 + 填充是我的错误,但你的解决方案有效。非常感谢。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-01-29
    • 1970-01-01
    • 1970-01-01
    • 2022-01-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多