简体   繁体   中英

How to update data by visually manipulating a chart

Is it possible at all to update data by visually manipulating a SVG object on a D3 chart? Or could point me in the right direction of where to find out how?

In this case, I am building a D3 Gantt chart and want to update an item's start and end date data by dragging the objects dates along the timeline.

In D3 you can manipulate both the DOM elements based on the data and the data based on the interaction with those elements. Keep in mind that the datum is just an object, that you can change anytime. In most D3 methods, it is the first argument in the callback.

Here is a very basic demo (since you didn't provide your code). There are three bars, foo , bar and baz , whose values are 2000 , 4000 and 1500 . The scale's domain goes from 0 to 5000 .

In the SVG I'm drawing the bars based on their data and according to the scale. However, I added a drag function that changes not only the DOM element itself but the data bound to it. This can be achieved with a callback like this:

function(d){
    //   ^--- the first argument is the datum
    d = whatever;//changing the datum
}

Here is the demo, drag the bars horizontally and look at the console:

 var data = [{ name: 'foo', value: 2000 }, { name: 'bar', value: 4000 }, { name: 'baz', value: 1500 }]; var svg = d3.select("svg"); var scale = d3.scaleLinear() .domain([0, 5000]) .range([0, 500]); var bars = svg.selectAll(null) .data(data) .enter() .append("rect") .attr("y", function(d, i) { return 10 + i * 30 }) .attr("height", 20) .attr("width", function(d) { return scale(d.value) }) .style("fill", "#666") .call(d3.drag().on("drag", function(d) { d.value = scale.invert(d3.mouse(this)[0]) d3.select(this).attr("width", scale(d.value)) console.log("datum: " + JSON.stringify(d)) })) 
  .as-console-wrapper { max-height: 25% !important;} 
 <script src="https://d3js.org/d3.v4.min.js"></script> <svg width="500" height="200"></svg> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM