【发布时间】:2021-04-26 09:20:19
【问题描述】:
我正在尝试在 d3.js 中绘制一个可缩放的相对简单的折线图。我一直在看这些例子。
简单的线条示例
https://observablehq.com/@d3/learn-d3-shapes?collection=@d3/learn-d3
https://www.d3-graph-gallery.com/graph/line_basic.html
缩放示例
https://observablehq.com/@d3/zoomable-area-chart
这是我的 jsfiddle。我的线路没有出现。
https://jsfiddle.net/tw5u2po9/
编辑:我的线现在正在工作,只是在进行缩放
https://jsfiddle.net/dc3g2uqm/
HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8"/>
</head>
<body>
<h1>My Chart</h1>
<div style="width:75%">
<canvas id="my_canvas"></canvas>
</div>
<div id="my_chart"></div>
</body>
</html>
CSS
.line {
fill: none;
stroke: #ffab00;
stroke-width: 3;
}
.overlay {
fill: none;
pointer-events: all;
}
/* Style the dots by assigning a fill and stroke */
.dot {
fill: #ffab00;
stroke: #fff;
}
.focus circle {
fill: none;
stroke: steelblue;
}
Javascript
var x = [new Date(2020, 10, 10), new Date(2020, 10, 11), new Date(2020, 10, 12), new Date(2020, 10, 13)]
var y = [5,6,8,4]
var data = {}
data.x = x;
data.y = y;
// 2. Use the margin convention practice
var margin = {top: 50, right: 50, bottom: 50, left: 50}
var width = window.innerWidth - margin.left - margin.right // Use the window's width
var height = window.innerHeight - margin.top - margin.bottom; // Use the window's height
// 5. X scale will use the index of our data
var xScale = d3.scaleUtc()
.domain([0 , d3.max(x)]) // input
.range([0, width]); // output
// 6. Y scale will use the randomly generate number
var yScale = d3.scaleLinear()
.domain([0, d3.max(y)]) // input
.range([height, 0]); // output
// 7. d3's line generator
var line = d3.line()
.x(function(d) { return xScale(d.x); }) // set the x values for the line generator
.y(function(d) { return yScale(d.y); }) // set the y values for the line generator
// 1. Add the SVG to the page and employ #2
var svg = d3.select("#my_chart").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 + ")");
// 3. Call the x axis in a group tag
svg.append("g")
.attr("class", "x axis")
.attr("transform", "translate(0," + height + ")")
.call(d3.axisBottom(xScale)); // Create an axis component with d3.axisBottom
// 4. Call the y axis in a group tag
svg.append("g")
.attr("class", "y axis")
.call(d3.axisLeft(yScale)); // Create an axis component with d3.axisLeft
// 9. Append the path, bind the data, and call the line generator
svg.append("path")
.datum(data) // 10. Binds data to the line
.attr("class", "line") // Assign a class for styling
.attr("d", line); // 11. Calls the line generator
【问题讨论】:
标签: javascript d3.js