D3.js-X轴未显示在散点图上

时间:2019-05-04 21:19:19

标签: d3.js svg scatter-plot

我正在尝试通过从.csv文件中加载数据来构建散点图。我的散点图试图显示每个州的贫困(x轴)与医疗保健(y轴)。

这是CSV文件的摘要:

id   state      healthcare  poverty
 1   Alabama      13.9      19.3
 2   Alaska       11.2      11.4
 3   Arizona      14.4      18.2
 4   Arkansas     16.3      18.9
 5   California   14.8      16.4
 6   Colorado     12.8      12
 7   Connecticut   8.7      10.8
 8   Delaware      8.7      12.5

这是我的JavaScript代码:

var svgWidth = 960;
var svgHeight = 500;

var margin = {
    top: 20,
    right: 40,
    bottom: 60, 
    left: 100
};

var width = svgWidth - margin.left - margin.right;
var height = svgHeight - margin.top - margin.bottom;

// Create an SVG wrapper, append an SVG group that will hold our chart and shift the latter by left and top margins
var svg = d3.select("#scatter")
  .append("svg")
  .attr("width", width)
  .attr("height", height);

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

// Import Data
d3.csv("data.csv").then(function(censusData) {

    // Parse Data & Cast as numbers
    censusData.forEach(function(data) {
      data.healthcare = +data.healthcare;
      data.poverty = +data.poverty;
    });

    // Create scale functions
    var xLinearScale = d3.scaleLinear()
      .domain(d3.extent(censusData, d => d.poverty))
      .range([0, width]);

    var yLinearScale = d3.scaleLinear()
      .domain([0, d3.max(censusData, d => d.healthcare)])
      .range([height, 0]);

    // Create axis functions
    var bottomAxis = d3.axisBottom(xLinearScale);
    var leftAxis = d3.axisLeft(yLinearScale);

    // Append axes to the chart
    chartGroup.append("g")
      .attr("transform", `translate(0, ${height})`)
      .call(bottomAxis);

    chartGroup.append("g")
      .call(leftAxis);

    // Create circles
    var circlesGroup = chartGroup.selectAll("Circle")
      .data(censusData)
      .enter()
      .append("circle")
      .attr("cx", d => xLinearScale(d.poverty))
      .attr("cy", d => yLinearScale(d.healthcare))
      .attr("r", "15")
      .attr("fill", "blue") 
      .attr("opacity", "0.5");

    // Create axes labels
    chartGroup.append("text")
      .attr("transform", "rotate(-90)")
      .attr("y", 0 - margin.left + 40)
      .attr("x", 0 - (height / 2))
      .attr("dy", "1em")
      .attr("class", "axisText")
      .text("Lacks Healthcare (%)");

    chartGroup.append("text")
      .attr("transform", `translate(${width / 2}, ${height + margin.top + 30})`)
      .attr("class", "axisText")
      .text("In Poverty (%)");

});

这是随附的HTML:

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <title>D3Times</title>
  <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo"
    crossorigin="anonymous"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js" integrity="sha384-ZMP7rVo3mIykV+2+9J3UJ46jBk0WLaUAdn689aCwoqbBJiSnjAK/l8WvCWPIPm49"
    crossorigin="anonymous"></script>
  <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js" integrity="sha384-ChfqqxuZUCnJSK3+MXmPNIyE6ZbWh2IMqE241rYiqJxyMiZ6OW/JmZQ5stwEULTy"
    crossorigin="anonymous"></script>
  <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO"
    crossorigin="anonymous">
  <link rel="stylesheet" href="assets/css/style.css">
  <link rel="stylesheet" href="assets/css/d3Style.css">

</head>

<body>
  <div class="container">
    <div class="row">
      <div class="col-xs-12 col-md-12">
        <h1>D3Times</h1>
      </div>
    </div>
    <div class="row">
      <div class="col-xs-12  col-md-9">
        <div id="scatter">
          <!-- We append our chart here. -->
        </div>
      </div>
    </div>
  </div>

  <!-- Footer-->
  <div id="footer">
    <p>The Coding Boot Camp&copy;2016</p>
  </div>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.5.0/d3.min.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/d3-tip/0.9.1/d3-tip.js"></script>
  <script type="text/javascript" src="assets/js/app.js"></script>

</body>

</html>

运行代码时,这是我得到的散点图:

my scatterplot

为什么X轴不显示?有人可以帮忙吗?

任何帮助将不胜感激!预先感谢。

P.S:要运行代码,我必须进入项目文件夹并运行 python -m http.server 这会将网页托管在网络浏览器的localhost:8000上。

1 个答案:

答案 0 :(得分:1)

您正在使用著名的margin convention创建数据视图:

enter image description here

但是,要使其正常工作,您必须使用总宽度和高度来设置SVG大小...

var svgWidth = 960;
var svgHeight = 500;

...不是去除边距后计算的值:

var width = svgWidth - margin.left - margin.right;
var height = svgHeight - margin.top - margin.bottom;

因此,应该是:

var svg = d3.select("#scatter")
    .append("svg")
    .attr("width", svgWidth)
    .attr("height", svgHeight);

这是您更新的代码:

var csv = `id,state,healthcare,poverty
1,Alabama,13.9,19.3
2,Alaska,15,11.2,11.4
3,Arizona,14.4,18.2
4,Arkansas,16.3,18.9
5,California,14.8,16.4
6,Colorado,12.8,12
7,Connecticut,8.7,10.8
8,Delaware,8.7,12.5`;

const censusData = d3.csvParse(csv)

var svgWidth = 960;
var svgHeight = 500;

var margin = {
  top: 20,
  right: 40,
  bottom: 60,
  left: 100
};

var width = svgWidth - margin.left - margin.right;
var height = svgHeight - margin.top - margin.bottom;

// Create an SVG wrapper, append an SVG group that will hold our chart and shift the latter by left and top margins
var svg = d3.select("#scatter")
  .append("svg")
  .attr("width", svgWidth)
  .attr("height", svgHeight);

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


// Parse Data & Cast as numbers
censusData.forEach(function(data) {
  data.healthcare = +data.healthcare;
  data.poverty = +data.poverty;
});

// Create scale functions
var xLinearScale = d3.scaleLinear()
  .domain(d3.extent(censusData, d => d.poverty))
  .range([0, width]);

var yLinearScale = d3.scaleLinear()
  .domain([0, d3.max(censusData, d => d.healthcare)])
  .range([height, 0]);

// Create axis functions
var bottomAxis = d3.axisBottom(xLinearScale);
var leftAxis = d3.axisLeft(yLinearScale);

// Append axes to the chart
chartGroup.append("g")
  .attr("transform", `translate(0, ${height})`)
  .call(bottomAxis);

chartGroup.append("g")
  .call(leftAxis);

// Create circles
var circlesGroup = chartGroup.selectAll("Circle")
  .data(censusData)
  .enter()
  .append("circle")
  .attr("cx", d => xLinearScale(d.poverty))
  .attr("cy", d => yLinearScale(d.healthcare))
  .attr("r", "15")
  .attr("fill", "blue")
  .attr("opacity", "0.5");

// Create axes labels
chartGroup.append("text")
  .attr("transform", "rotate(-90)")
  .attr("y", 0 - margin.left + 40)
  .attr("x", 0 - (height / 2))
  .attr("dy", "1em")
  .attr("class", "axisText")
  .text("Lacks Healthcare (%)");

chartGroup.append("text")
  .attr("transform", `translate(${width / 2}, ${height + margin.top + 30})`)
  .attr("class", "axisText")
  .text("In Poverty (%)");
<head>
  <meta charset="UTF-8">
  <title>D3Times</title>
  <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js" integrity="sha384-ZMP7rVo3mIykV+2+9J3UJ46jBk0WLaUAdn689aCwoqbBJiSnjAK/l8WvCWPIPm49" crossorigin="anonymous"></script>
  <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js" integrity="sha384-ChfqqxuZUCnJSK3+MXmPNIyE6ZbWh2IMqE241rYiqJxyMiZ6OW/JmZQ5stwEULTy" crossorigin="anonymous"></script>
  <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous">
  <link rel="stylesheet" href="assets/css/style.css">
  <link rel="stylesheet" href="assets/css/d3Style.css">

</head>

<body>
  <div class="container">
    <div class="row">
      <div class="col-xs-12 col-md-12">
        <h1>D3Times</h1>
      </div>
    </div>
    <div class="row">
      <div class="col-xs-12  col-md-9">
        <div id="scatter">
          <!-- We append our chart here. -->
        </div>
      </div>
    </div>
  </div>

  <!-- Footer-->
  <div id="footer">
    <p>The Coding Boot Camp&copy;2016</p>
  </div>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.5.0/d3.min.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/d3-tip/0.9.1/d3-tip.js"></script>
  <script type="text/javascript" src="assets/js/app.js"></script>

</body>