1

我正在使用 D3 和 JQuery Slider 生成一个热图,当我更改滑块的光标位置(代表色标范围)时,它的颜色会自动刷新。虽然当我第一次单击滑块时它工作正常,但之后似乎并没有刷新。如果您想指出我的错误,我会发布来源:

<HEAD>
<TITLE>Heatmap</TITLE>
</HEAD>
<BODY BGCOLOR="WHITE">

<CENTER>
<H1>Heatmap</H1>

<H5>Heatmap should instantly display bidimensional data (adjustable thresholds)</H5>




<script src="http://d3js.org/d3.v3.min.js"></script>
<link rel="stylesheet" href="http://code.jquery.com/ui/1.9.2/themes/base/jquery-ui.css" />
<script src="http://code.jquery.com/jquery-1.8.3.js"></script>
<script src="http://code.jquery.com/ui/1.9.2/jquery-ui.js"></script>
<link rel="stylesheet" href="/resources/demos/style.css" />

<div id="slider"></div>
<p>
 <div id="heatmap"></div>

<script>

var minval= 0;
var maxval= 1000;


$( "#slider" ).slider({
    range: true,
    min: 0,
    max: 1000,
    values: [0, 1000],
    slide: function( event, ui ) {
      var minval = ui.values[0];
      var maxval = ui.values[1];
      console.log("begin:", minval, "end:", maxval);
      draw(minval, maxval); 
    }
});


var margin = {top: 0, right: 20, bottom: 20, left: 20},
    width = 300 - margin.left - margin.right,
    height = 300 - margin.top - margin.bottom;

var svg = d3.select("#heatmap").append("svg:svg");

var data = [[1000,500,1],[500,1,1000],[1000,54,800]];

var x = d3.scale.linear()
    .range([0, width])
    .domain([0,data[0].length]);

var y = d3.scale.linear()
    .range([0, height])
    .domain([0,data.length]);

svg.attr("width", width + margin.left + margin.right)
        .attr("height", height + margin.top + margin.bottom)
        .append("g")
        .attr("transform", "translate(" + margin.left + "," + margin.top + ")");

var colorLow = 'white', colorMed = 'green', colorHigh = 'red';


function draw(minval,maxval){

    var colorScale = d3.scale.linear()
         .domain([minval, maxval])
         .range([colorLow, colorHigh]);

    var row = svg.selectAll(".row")
            .data(data)
            .enter().append("svg:g")
            .attr("class", "row");

    var col = row.selectAll(".cell")
               .data(function (d,i) { return d.map(function(a) { return {value: a, row: i}; } ) })
               .enter().append("svg:rect")
                 .attr("class", "cell")
                 .attr("x", function(d, i) { return x(i); })
                 .attr("y", function(d, i) { return y(d.row); })
                 .attr("width", x(1))
                 .attr("height", y(1))
                 .style("fill", function(d) { return colorScale(d.value); });

}



</script>
</head>
<body>

</CENTER>
</body>
4

1 回答 1

3

它第二次不起作用,因为您正在对选择进行操作,第二次调用.enter()它将为空,因为元素已经存在。draw()

要解决此问题,请将声明移到row函数col之外draw()。在draw()函数内部,只保留实际更改的代码。就像是

function draw(minval,maxval){
    var colorScale = d3.scale.linear()
         .domain([minval, maxval])
         .range([colorLow, colorHigh]);
    col.style("fill", function(d) { return colorScale(d.value); });
}
于 2013-01-08T18:46:00.880 回答