【问题标题】:Use d3 to create InnerWidth and InnerHeight so grid isn't on the border使用 d3 创建 InnerWidth 和 InnerHeight 使网格不在边框上
【发布时间】:2019-04-09 07:31:26
【问题描述】:

我尝试制作的图表正好在边框上,我尝试包含内边距,以便我可以在外边距中留出空间,但它不起作用。有什么建议? 我正在使用 d3.js 谢谢

// D3 gives us an api to allow us to create axises
// d3.axisTop()
// d3.axisRight()
// d3.axisBottom()
// d3.axisLeft()

var data= [80, 100, 56, 120, 180, 30, 40, 120, 160];
var data1= [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15]
var margin = {top:20, right: 20, bottom: 20, left: 20};
var InnerWidth = 500, InnerHeight = 300;

var svg = d3.select('svg') //applying the width and high of the svg box
   .attr("width", InnerWidth)
   .attr("height", InnerHeight);


var xScale = d3.scaleLinear()
   .domain([0, d3.max(data)]) //takes in integers between 0 to max integer
   .range([0, 400]); //represents the length of the x-axis

var yScale = d3.scaleLinear()
   .domain([0, d3.max(data1)]) //this the range of the data from 0 to max
   .range([InnerHeight, 0]);   //represents the length of the x-axis

var x_axis = d3.axisBottom().scale(xScale); //call for x-axis

var y_axis = d3.axisLeft().scale(yScale);   //call for y-axis

svg.append("g")                             //group element
   .attr("transform", "translate(50, 0)")  //takes the y-axis and transforms it(shift it)
   .call(y_axis);

var xAxisTranslate = InnerHeight - 20;

svg.append("g")
   .attr("transform", "translate(50, " + xAxisTranslate  +")")
   .call(x_axis);

svg.append("g")
  .attr("transform","translate(${margin.left},${margin.top})");


<html>
    <head>
        <link rel="stylesheet" href="index.css">
        <title>Learn D3.js</title>
    </head>
    <body>
        <h1>Bar Chart using D3.js</h1>

        <svg></svg>

        <script src="https://d3js.org/d3.v4.min.js"></script>
        <script src="index.js"></script>
    </body>
</html>

【问题讨论】:

    标签: d3.js svg height width


    【解决方案1】:

    请尝试将 SVG 元素的 widthheight 替换为 viewBox,如下所示:

    var svg = d3.select('svg') 
       //.attr("width", InnerWidth)
       //.attr("height", InnerHeight);
       .attr("viewBox", `${-margin.right} ${-margin.top} ${InnerWidth + 2*margin.right} ${InnerHeight + 2*margin.top}`);
    

    我希望这会有所帮助。

    【讨论】:

      猜你喜欢
      • 2014-10-21
      • 2019-02-26
      • 1970-01-01
      • 1970-01-01
      • 2020-11-10
      • 2013-07-24
      • 2020-10-09
      • 2019-11-18
      • 2021-09-16
      相关资源
      最近更新 更多