Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
150 views
in Technique[技术] by (71.8m points)

javascript - How do I draw a zoomable d3 line chart over time?

I'm trying to draw a relatively simple line chart in d3.js that is zoomable. I have been looking at these examples.

Simple line examples

https://observablehq.com/@d3/learn-d3-shapes?collection=@d3/learn-d3

https://www.d3-graph-gallery.com/graph/line_basic.html

Zooming example

https://observablehq.com/@d3/zoomable-area-chart

Here is my jsfiddle. My line is not showing up.

https://jsfiddle.net/tw5u2po9/

Edit: my line is working now just working on the zooming

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 

question from:https://stackoverflow.com/questions/65836159/how-do-i-draw-a-zoomable-d3-line-chart-over-time

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

For the line and x-axis issues:

  • data should be in format {"x": date obj, "y": number}
  • x-axis domain should be d3.min and d3.max of the dates

For zooming, d3 v6 has an update to use event in a different way.

I think this d3 v5 example of line chart zooming is easier to adapt than the observable you mentioned - see the zoom function below and compare to the original block.

Note the svg defs adding a clippath that becomes an attribute of the x-axis and line. This will stop the zoomed portion of the chart 'spilling over' to the left and right.

// Prep data
/* 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 x = d3.timeDays(new Date(2020, 06, 01), new Date(2020, 10, 30));
var y = Array.from({length: x.length}, Math.random).map(n => Math.floor(n * 10) + 5);
var data = x.map((v, i) => {
  return {
    "x": v,
    "y": y[i]
  }
});

  
// Use the margin convention practice 
var margin = {top: 50, right: 50, bottom: 50, left: 50}
var width = 600 - margin.left - margin.right // Use the window's width 
var height = 400 - margin.top - margin.bottom; // Use the window's height

// zoom function for d3v6
// adapt to v6 from this v5 block https://bl.ocks.org/LemoNode/7ac1d41fe75fe7d2d9cb85e78aad6303
var zoom = d3.zoom()
  .on('zoom', (event) => {
    xScale
      .domain(event.transform.rescaleX(xScale2).domain())
      .range([0, width].map(d => event.transform.applyX(d))); //
      
    svg.select(".line")
        .attr("d", line); // zooms line

      svg.select(".x-axis")
        .call(d3.axisBottom(xScale)
      .tickSizeOuter(0)); // zooms axis
  })
  .scaleExtent([1, 32]); // adjust 32 to less zoom less


// X scale - use min and max of scale
var xScale = d3.scaleUtc()
  .domain([d3.min(x), d3.max(x)]) // input
  .range([0, width]); // output

// constant reference point whilst zooming
var xScale2 = d3.scaleUtc()
  .domain([d3.min(x), d3.max(x)]) // input
  .range([0, width]); // output  
  
// Y scale - add 5 for bit of whitespace at top of graph
var yScale = d3.scaleLinear()
  .domain([0, d3.max(y) + 5]) // input 
  .range([height, 0]); // output 

// 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 

// 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)
  .call(zoom) // call the zoom
  .append("g")
  .attr("transform", "translate(" + margin.left + "," + margin.top + ")");

// clippath to stop line and x-axis 'spilling over'
svg.append("defs").append("clipPath")
  .attr("id", "clip")
  .append("rect")
  .attr("x", 0)
  .attr("width", width)
  .attr("height", height);
    
// call x-axis and apply the clip from the defs
svg.append("g")
  .attr("class", "x-axis")    
  .attr("clip-path", "url(#clip)") // add the clip path!
  .attr("transform", "translate(0," + height + ")")
  .call(d3.axisBottom(xScale)); // Create an axis component with d3.axisBottom

// Call the y-axis 
svg.append("g")
  .attr("class", "y-axis")
  .call(d3.axisLeft(yScale)); // Create an axis component with d3.axisLeft
    
// 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("clip-path", "url(#clip)") // add the clip path!
  .attr("d", line); // 11. Calls the line generator
.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;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/6.0.0/d3.min.js"></script>
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8"/>
</head>
<body>
  <div id="my_chart"></div>
</body>
</html>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...