【发布时间】:2021-07-14 14:58:48
【问题描述】:
我是 d3 的新手,我正在尝试使用我找到的示例绘制基本散点图。我没有在示例中使用读取 csv 函数,而是尝试添加自己的数据。
使用以下代码,它显示轴,但仅在 [0,10] 处显示单个点。见下图。我可能会错过什么?
// set the dimensions and margins of the graph
var margin = {top: 10, right: 30, bottom: 30, left: 60},
width = 460 - margin.left - margin.right,
height = 400 - margin.top - margin.bottom;
// append the svg object to the body of the page
var svg2 = d3.select("#my_dataviz2")
.append("svg")
.attr("width", width + margin.left + margin.right)
.attr("height", height + margin.top + margin.bottom)
.append("g")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")");
//Read the data
var data = [
{"name": "point1", "x":1, "y":2},
{"name": "point2", "x":3, "y":4},
{"name": "point3", "x":5, "y":6},
{"name": "point4", "x":7, "y":8}
];
// Add X axis
var x = d3.scaleLinear()
.domain([0, 10])
.range([ 0, width ]);
svg2.append("g")
.attr("transform", "translate(0," + height + ")")
.call(d3.axisBottom(x));
// Add Y axis
var y = d3.scaleLinear()
.domain([0, 10])
.range([ height, 0]);
svg2.append("g")
.call(d3.axisLeft(y));
// Add dots
svg2.append("g")
.selectAll("dot")
.data(data)
.enter()
.append("circle")
.attr("r", 3.5)
.style("fill", "#000");
<script src="https://cdn.jsdelivr.net/npm/d3@7"></script>
<div id="my_dataviz2"></div>
【问题讨论】:
标签: javascript html d3.js