I am attempting to create a simple bar graph that updates when you change a slider value, I am having a couple of issues. I don't know how to update a attribute of the svg element when changing the slider without drawing a whole new svg element thus creating two, three four elements.....

you can view it at jsfiddle

Here is my code

$( "#slider" ).slider({ max: 50 });

$( "#slider" ).slider({ min: 10 });



$( "#slider" ).slider({
  change: function( event, ui ) {
   var selection = $( "#slider" ).slider( "value" );
    console.log(selection);



                //Width and height
            var w = 500;
            var h = 50;

            //Data
            var dataset = [];

      dataset.push(selection);

      console.log(dataset);

            //Create SVG element
            var svg = d3.select("body")
                        .append("svg")
                        .attr("width", 500)
                        .attr("height", 50);

            var rectangle = svg.selectAll("rect")
            .data(dataset)
            .enter()
            .append("rect");





            rectangle.attr("width", 20)

            .attr("height", function(d){
                return d;
            })
            .attr("x", function(d){
                return 20;
            })
            .attr("y", function(d){
                return 20;
            });


  }
});
有帮助吗?

解决方案

Just a couple of changes were necessary.

Change to the handling of the enter/update selection:

var rectangle = svg.selectAll("rect")
    .data(dataset);

rectangle
    .enter()
    .append("rect");

rectangle
    .attr("width", 20)
    ...

Change to the placement of the SVG element outside the slider handler.

Complete FIDDLE.

NOTE: the current height of the SVG element is not sufficient to see the magnitude of changes allowed by the slider. You should increase that, say attr("height", 200).

Another FIDDLE responding to the slide event and thus making the change to the rect's height more pleasing to the eye.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top