首页 > 解决方案 > D3:图表不显示 x 和 y 轴

问题描述

我有这个 d3 项目,但我似乎无法正确显示我的 x 和 y 轴。它仅显示 y 轴上的前 2 个数字,仅此而已。任何人都可以帮助我为什么它没有显示。我在这里想念什么?

这是代码:

loadData = ()=> {
  req = new XMLHttpRequest();
  req.open("GET", "https://raw.githubusercontent.com/freeCodeCamp/ProjectReferenceData/master/GDP-data.json" , true);
  req.send();
  req.onload= ()=>{
      json = JSON.parse(req.responseText);
      //create measurements
      const margin = 60
      const width = 1000 - margin;
      const height = 600 - margin;

      //create svg
      const svg = d3.select("svg");
      const chart = svg.append("g")
        .attr("transform", `translate(${margin}, ${margin})`);


      //y-axis: split charts into 2 equal parts using scaling function
      const yScale = d3.scaleLinear()
        .range([height, 0]) //length
        .domain([0,100]); //content

      //create x-axis
      const yAxis = d3.axisLeft(yScale);

      //append y-axis
      chart.append("g")
        .call(yAxis);

       //create x-scale
      const xScale = d3.scaleBand()
        .range([0, width]) //length
        .domain([0,100]) //content
        .padding(0.2);

      //create x-axis
      const xAxis = d3.axisBottom(xScale);

      //append x-axis
      chart.append("g")
        .attr(`transform`, `translate(0, ${height})`)
        .call(xAxis);
   } 
}

loadData();

这是我的代码笔: 代码笔

标签: javascriptd3.jscharts

解决方案


您正在使用 w1000、h600 (+margin) 的窗格大小。相应地调整 SVG 元素(在 CSS 中)的大小,图表将按预期显示:

svg {
  width: 1030px;
  height: 630px;
}

PS:或者在您的 JS 代码中设置 svg 大小,因此您只需在一个地方定义这些数字。


推荐阅读