首页 > 解决方案 > 使用 Viewbox 调整绘图轴的大小

问题描述

我试图让自己熟悉可调整大小的 d3 图。但是,我的绘图的 x 轴和 y 轴有问题。

窗口大小低于某个阈值后,x 轴显示为白色背景(而不是蓝色)。此外,由于我无法缩短轴,因此 y 轴的最高值被截断。此外,当窗口尺寸太小时,y 轴会完全消失。

我还尝试将两个轴都放在矩形内(由注释标记),但它们根本不显示。

如您所见,我正在使用引导程序来构成 HTML 中的样式。关于调整大小,我正在寻找带有 Viewbox 的仅 JavaScript 解决方案,如代码中所示。

简而言之,盒子似乎可以调整大小,而轴却没有。

我错过了什么?非常感谢您的帮助!

这是我的代码:

<div class="container-fluid bg-info">
    <div class="row">
        <div class="col-auto">
            <h5>some title</h5>
        </div>
    </div>
    <div class="row justify-content-center">

        <div id="plot"></div>

    </div>

</div>

<div class="row mt-3"></div>

<script src="./js/d3.js"></script>

<script>

    var height = 500;
    var width = 500;
    var margin = { top: 20, right: 20, bottom: 50, left: 0 };
    

    var svg = d3.select("#plot")
        .append("div")
        .classed("svg-container", true)
        .append("svg")
        .attr("width", width)
        .attr("height", height + margin.top + margin.bottom)
        .attr("preserveAspectRatio", "xMinYMin meet")
        .attr("viewBox", "0 0 " + width + " " + height)
        .classed("svg-content-responsive", true);

    svg.append("rect")//tried to insert axis insight this rect, however they disappeard
        .classed("rect", true)
        .attr("width", width)
        .attr("height", height)
        .attr("fill", "white");

    var xAchsis = d3.scaleLinear()
        .domain([0, 85000000])
        .range([0, width]);

    svg.append("g")
        .attr("transform", "translate(80," + height + ")")
        .call(d3.axisBottom(xAchsis));

    svg.append("text")
        .attr("class", "x label")
        .attr("text-anchor", "end")
        .attr("x", 300)
        .attr("y", 550)
        .text("x-label");

    var yAchsis = d3.scaleLinear()
        .domain([0, 400000])
        .range([height, 0]);

        svg.append("g")
        .call(d3.axisLeft(yAchsis))
        .attr("transform", "translate(80 ,0)");

        svg.append("text")
        .attr("class", "y label")
        .attr("text-anchor", "end")
        .attr("y", -10)
        .attr("x", 250)
        .attr("transform", "rotate(90)")
        .text("y-label");
</script>

标签: javascriptd3.jsresizeaxis

解决方案


推荐阅读