Reputation: 1068
someone knows why I have a completely srewed up layout in my d3 scales while entering or updating array values between 5 and 9 and bigger than 100 ?
I have setted up here the example: http://bl.ocks.org/vertighel/5149663
As you can see from the code and in this picture, the bar chart must not exceed a width of 500px and a color of orange... but try to insert a value between 5 and 9 or bigger than 100 and you'll see. Let's change the "11" in "9":
width and color scale completely screwed up!
This is the code:
<!doctype html>
<meta charset="utf8"></meta>
<title>Test</title>
<style type="text/css">
li{border: 1px solid white; background-color: steelblue; color: white}
li{width: 50px; text-align:right; }
li:hover{opacity:0.7;}
.clicked{background-color: green}
:invalid{background-color: pink}
</style>
<body>
<script src="http://d3js.org/d3.v3.min.js"></script>
<input id="inp" value="1,23,42,20,11,33,21" pattern="(\d+)(,\s*\d+)*" required>
<label for="inp">change me</label>
<h1>click on the bars</h1>
<script>
var list = d3.select("body").append("ul");
update()
d3.select("input").on("change",update)
function update(){
var array = d3.select("input").property("value").split(",")
console.log(array);
var cscale = d3.scale.linear()
.domain(d3.extent(array))
.range(["steelblue","orange"])
var wscale = d3.scale.linear()
.domain(d3.extent(array))
.range(["10px","500px"])
var elem = list.selectAll("li").data(array);
elem.enter()
.append("li")
elem.text(function(d){return d})
.transition()
.style("width", function(d){return wscale(d)})
.style("background-color", function(d){return cscale(d)})
elem.on("click",function(d,i){d3.select("h1").text("list item "+i+" has value "+d)})
elem.exit().remove()
}
</script>
Upvotes: 0
Views: 367
Reputation: 109242
You're seeing this because your numbers aren't actually numbers, but strings. In particular, a "9" is only one character long while all your other "numbers" are two characters long (similarly for "100").
The solution is to convert your strings into integers. One way of doing this is to use the map()
function as follows. Replace
var array = d3.select("input").property("value").split(",")
to
var array = d3.select("input").property("value").split(",")
.map(function(d) { return(+d); });
The map()
function may or may not be implemented in your setup, see here for more information and an implementation you can use.
Upvotes: 2