I have this bar chart on D3.js... It works fine..
But I'm having problems with the scale... When a data series has a value much grater than the others, the <rect> does not fit into the scale.
Any idea how to solve this matter?
Here is the code:
var data = [
{"Anio":"1999","CONTRAVENCIONAL":"78484","PENAL":"0","FALTAS":"0","MULTAS":"0","OTROS":"0","TOTAL":"78484"},
{"Anio":"2000","CONTRAVENCIONAL":"92879","PENAL":"0","FALTAS":"0","MULTAS":"0","OTROS":"0","TOTAL":"92879"},
{"Anio":"2001","CONTRAVENCIONAL":"100018","PENAL":"0","FALTAS":"1818","MULTAS":"0","OTROS":"0","TOTAL":"101836"},
{"Anio":"2002","CONTRAVENCIONAL":"101380","PENAL":"0","FALTAS":"3692","MULTAS":"0","OTROS":"0","TOTAL":"105072 "},
{"Anio":"2003","CONTRAVENCIONAL":"86791","PENAL":"0","FALTAS":"7417","MULTAS":"0","OTROS":"0","TOTAL":"94208"},
{"Anio":"2004","CONTRAVENCIONAL":"47870","PENAL":"255","FALTAS":"1105","MULTAS":"1811","OTROS":"0","TOTAL":"51041"},
{"Anio":"2005","CONTRAVENCIONAL":"33013","PENAL":"348","FALTAS":"1473","MULTAS":"634","OTROS":"0","TOTAL":"35468"},
];
var margin = {top: 20, right: 30, bottom: 30, left: 40},
width = 860 - margin.left - margin.right,
height = 400 - margin.top - margin.bottom;
var x = d3.scale.ordinal()
.rangeRoundBands([0, width], .1);
var y = d3.scale.linear()
.range([height, 0]);
var xAxis = d3.svg.axis()
.scale(x)
.orient("bottom");
var yAxis = d3.svg.axis()
.scale(y)
.orient("left");
var arr_data = [];
for (var i = 0; i < data.length; i++) {
var o = {'name':data[i].Anio,'value':data[i].TOTAL};
arr_data.push(o);
};
var chart = d3.select(".chart")
.attr("width", width + margin.left + margin.right)
.attr("height", height + margin.top + margin.bottom )
.append("g")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")");
x.domain(arr_data.map(function(d) { return d.name; }));
y.domain([0, d3.max(arr_data, function(d) { return d.value; })]);
chart.append("g")
.attr("class", "x axis")
.attr("transform", "translate(0," + height + ")")
.call(xAxis);
chart.append("g")
.attr("class", "y axis")
.call(yAxis);
var bar = chart.selectAll(".bar")
.data(arr_data)
.enter().append("g");
bar.append("rect")
.attr("class", "rect")
.attr("x", function(d) { return x(d.name); })
.attr("y", function(d) { return y(d.value) ; })
.attr("height", function(d) { return height - y(d.value); })
.attr("width", x.rangeBand())
.attr("fill","#632423")
.on('mouseover',function(d){
var a = d3.select(this)
.attr("fill","#733A39");
var a = d3.select("#tooltip")
.style("left","100px")
.style("top","20px")
.select("#value")
.text(d.value);
}).on('mouseout',function(d){
var a = d3.select(this)
.attr("fill","#632423"); //old color: #790018
});
bar.append("text")
.attr("class", "label")
.text(function(d) { return d.value; })
.attr("x", function(d) { return x(d.name)+4; })
.attr("y", function(d) { return y(d.value)+20 ; });
Your scale will actually handle series with larger values for you because you're dynamically setting it to go from 0 to the max value in your data:
y.domain([0, d3.max(arr_data, function(d) { return d.value; })]);
However, you're not converting your data to numbers from strings, so right now the scale is from [0, 94208] instead of [0, 105072]. This is because the character "9" is greater than "1". You can fix this by converting the values to numbers when you construct your arr_data, like this:
var o = {'name':data[i].Anio,'value':+data[i].TOTAL}; // <---- notice the '+'
This produces a better looking graph:
Related
I have to implement a bar chart in D3, but my values on the x axis are of type Date, data type which the D3 library should accept, but it seems to give me an error like this: attribute x: Expected length, "NaN".
This is the code for my bar chart:
//this holds the data that will be drawn
var data = [ {"yy":12,"mm":01,ppm_value:90000}, {"yy":11,"mm":02,ppm_value:50000}];;
//formats the date
var format = d3.time.format("%Y-%m-%d");
//define margins, height and width
var margin = {
top: 20,
right: 30,
bottom: 30,
left: 40
},
w = 1000 - margin.left - margin.right,
h = 500 - margin.top - margin.bottom;
/*var x = d3.time.scale()
//.domain([0, d3.max(data, function(d) { return d.date; })])
.range([0, w], 0.6);*/
var x = d3.time.scale()
.range([0, w]);
var y = d3.scale.linear()
//.domain([0, d3.max(data, function(d) { return d.ppm_value;})])
.range([h, 0]);
var xAxis = d3.svg.axis()
.scale(x)
.orient("bottom")
//.tickFormat(d3.time.format("%Y/%m"));
var yAxis = d3.svg.axis()
.scale(y)
.orient("left");
var zoom = d3.behavior.zoom()
.scaleExtent([1, 1])
.x(x)
.on("zoom", zoomed);
//create the svg
var chart = d3.select("#testChart").append("svg")
.attr("width", w + margin.left + margin.right)
.attr("height", h + margin.top + margin.bottom)
.append("g")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")")
.call(zoom);
var rect = chart.append("rect")
.attr("width", w)
.attr("height", h)
.style("fill", "none")
.style("pointer-events", "all");
//loops through data
data.forEach(function (d) {
//coerce to number
d.ppm_value = +d.ppm_value;
d.yy = +d.yy;
d.mm = +d.mm;
d.date = new Date("20" + d.yy + "/" +d.mm);
var dateTick = format(d.date);
d.date = dateTick;
console.log(d.ppm_value);
//console.log(dateTick);
//console.log(d.date);
});
//var dates = data.map(function(d){ return new Date("2016/01/03"); });
//console.log(formDate);
//map values onto x axis
x.domain([d3.min(data, function(d) { return d.date; }), d3.max(data, function(d) { return d.date; })])
// x.domain([0, d3.max(function(d) { return d.date; })]);
//map values onto y axis
y.domain([0, d3.max(data, function(d) { return d.ppm_value; })]);
chart.append("g")
.attr("class", "x axis")
.attr("transform", "translate(0," + h + ")")
.call(xAxis)
chart.append("g")
.attr("class", "y axis")
.call(yAxis);
var bars = chart.append("g")
.attr("class", "chartobjects");
bars.selectAll(".rect")
.data(data)
.enter().append("rect")
.attr("class", "rectBar")
.on("click",hello)
.attr('x', function(d) {
console.log(d.date);
return x(new Date(d.date));
})
.attr("y", function(d) {
return y(d.ppm_value);
console.log(d.ppm_value);
})
.attr("height", function(d) {
return h - y(d.ppm_value);
})
.attr("width", 15)
.attr("fill", function(d) {
return d.ppm_value > 6 ? "blue" : "red"
});
function hello() {
alert("Hello world!!")
}
function zoomed() {
console.log("Entered zoom function!!!");
var tx = Math.max(0, d3.event.translate[0])
//ty = Math.min(0, d3.event.translate[1]);
zoom.translate([tx]);
bars.attr("transform", "translate(" + [tx] + ")scale(" + d3.event.scale + ")");
chart.select(".x.axis")
.call(xAxis);
//chart.select(".y.axis")
// .call(yAxis);
}
I can not seem to get to the root of the problem. Am I doing something wrong ? What is the problem in your opinion ?
Thanks in advance!
I am using this http://bl.ocks.org/mbostock/3885304 reference for drawing Bar Char using Meteor and D3
This code returns y Axis is 0 and height always same.....
CODE PART
var margin = {top: 20, right: 20, bottom: 30, left: 40},
width = 960 - margin.left - margin.right,
height = 500 - margin.top - margin.bottom;
var xScale = d3.scale.ordinal()
.rangeRoundBands([0, width], .1);
var yScale = d3.scale.linear()
.range([height, 0]);
var xAxis =d3.svg.axis()
.scale(xScale)
.orient("bottom");
var yAxis = d3.svg.axis()
.scale(yScale)
.orient("left");
var svg = d3.select('#Rectangle')
.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 + ")");
var drawCircles = function(error,update) {
if (error) throw error;
var data = Extra.find().fetch();
xScale.domain(data.map(function(d) { return d.inst; }));
yScale.domain([0, d3.max(data, function(d) { return d.percent; })]);
svg.append("g")
.attr("class", "x axis")
.attr("transform", "translate(0," + height + ")")
.call(xAxis);
svg.append("g")
.attr("class", "y axis")
.call(yAxis)
.append("text")
.attr("transform", "rotate(-90)")
.attr("y", 6)
.attr("dy", ".71em")
.style("text-anchor", "end")
.text("Percentaz");
svg.selectAll('rect')
.data(data)
.enter()
.append('rect')
.attr("x", function(d) { return xScale(d.inst); })
.attr("y", function(d) { return yScale(d.percent); })
.attr("width", xScale.rangeBand())
.attr("height", function(d) { return height-yScale(d.percent); });
};
Extra.find().observe({
added: function () {
x =[];
var f = Extra.find().fetch() ;
for(var i=0;i<f.length;i++){
x.push(parseInt(f[i].percent))
}
drawCircles(false);
},
changed: _.partial(drawCircles, true)
});
};
Please provide me solution regarding this so i can implement it
I am having an issue using d3 to create a bar chart where the column overflows the and the y axis labels are incorrect. Here is a fiddle http://jsfiddle.net/fajgvj9v/ that shows the issue. The data is parsing the <pre id="data"> tag to simulate a CSV I am using. If you change the value of 'a' to 5000 from 4000 it renders as expected.
<pre id="data">
name,count
a, 4000
b, 500
</pre>
yTitle = "Items";
var margin = {
top: 20,
right: 20,
bottom: 30,
left: 40
},
width = 960 - margin.left - margin.right,
height = 500 - margin.top - margin.bottom;
var x = d3.scale.ordinal()
.rangeRoundBands([0, width], .1);
var xAxis = d3.svg.axis()
.scale(x)
.orient("bottom");
var y = d3.scale.linear()
.rangeRound([height, 0]);
var yAxis = d3.svg.axis()
.scale(y)
.orient("left")
.tickFormat(d3.format(".2s"));
var svg = d3.select("#malware_by_os").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 + ")");
var data = d3.csv.parse( d3.select("pre#data").text() );
console.log(data);
var xLbl = d3.keys(data[0])[0];
var yLbl = d3.keys(data[0])[1];
data.sort(function(a, b) {
return b[yLbl] - a[yLbl];
});
x.domain(data.map(function(d) {
return d[xLbl];
}));
y.domain([0, d3.max(data, function(d) {
return d[yLbl];
})]);
svg.append("g")
.attr("class", "x axis")
.attr("transform", "translate(0," + height + ")")
.call(xAxis);
svg.append("g")
.attr("class", "y axis")
.call(yAxis)
.append("text")
.attr("transform", "rotate(-90)")
.attr("y", 6)
.attr("dy", ".71em")
.style("text-anchor", "end")
.text(yTitle);
svg.selectAll(".bar")
.data(data)
.enter().append("rect")
.attr("class", "bar")
.attr("x", function(d) {
return x(d[xLbl]);
})
.attr("width", x.rangeBand())
.attr("y", function(d) {
return y(d[yLbl]);
})
.attr("height", function(d) {
return height - y(d[yLbl]);
});
The max function needs to convert to a number using +
y.domain([0, d3.max(data, function(d) {
return d[yLbl];
})]);
should be
y.domain([0, d3.max(data, function(d) {
return +d[yLbl];
})]);
I am having a lot of trouble with D3 bar chart where the length of the data I get from search is variable. I used the D3 bar chart example and built this. However as data length goes up, the graph gets less and less legible. The problem seems to be the range gets confused when it is beyond 100 points or so.
Code is below:
function makegraph(data,ctype) {
//var data=xdata.splice(-900)
var gwidth=data.length*2;
if(gwidth < 800) gwidth=800;
//gwidth=800
var margin = {top: 9, right: 20, bottom: 30, left: 90},
width = gwidth - margin.left - margin.right,
height = 300 - margin.top - margin.bottom;
x = d3.scale.ordinal()
.rangeRoundBands([0, width], .1);
//x=d3.scale.linear().domain([0,1]).range(0,width)
var y = d3.scale.linear()
.range([height, 0]);
var xAxis = d3.svg.axis()
.scale(x)
.orient("bottom")
.tickFormat(function(d) { if (d % 10) return ""; else return d;})
var yAxis = d3.svg.axis()
.scale(y)
.orient("left");
// .ticks(10, "%");
d3.select("svg").remove()
var svg = d3.select("#graphchart").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 + ")");
var line = d3.svg.line()
.x(function(d) { return x(d.rowid); })
.y(function(d) { return y(d[ctype]); });
x.domain(data.map(function(d) { return d.rowid; }));
var ymax=d3.max(data, function(d) { return d[ctype]; });
var ymin=d3.min(data, function(d) { return d[ctype]; });
y.domain([ymin, ymax]);
svg.append("g")
.attr("class", "x axis")
.attr("transform", "translate(0," + height + ")")
.call(xAxis);
svg.append("g")
.attr("class", "y axis")
.call(yAxis)
.append("text")
.attr("transform", "rotate(-90)")
.attr("y", Math.log10(ymax))
.attr("dy", ".71em")
.style("text-anchor", "end")
.text("Bytes");
// console.log(x.rangeBand())
var bar = svg.selectAll(".bar")
.data(data);
bar.enter().append("rect")
.attr("class", "bar")
.attr("x", function(d) { return x(d.rowid); })
.attr("width", x.rangeBand())
.attr("y", function(d) { return y(d[ctype]); })
.attr("height", function(d) { var xya= height - y(d[ctype]); /* console.log(xya+":"+d[ctype]); */ return height - y(d[ctype]); })
/* .attr("title", function(d) { return d['bytes']+" Bytes at "+d.stime; }) */
.on("mouseover", function(d) { $("#graphinfo").html(d3.format('0,000')(d['bytes'])+" Bytes at "+d.stime) })
.on("mouseout",function(d) { $("#graphinfo").html(' ')})
.on("click",function(d) { tablegraph(d)});
$('.bar').tooltip()
}
Do you have suggestions how I can make this graph so that the bar chart will grow horizontally for larger data sets? Thanks for any help and suggestions!
Vijay
I am creating a bar chart using d3. To do so I looked at this code and changed it a little bit.
However what it does is centering the bars, and I would like the bars to start immediate at the bar y axis.
It looks like the issue comes from these 2 pieces of code:
var x = d3.scale.ordinal()
.rangeRoundBands([0, width], .0);
and the last line of this one:
svg.selectAll(".bar")
.data(graphObj)
.enter().append("rect")
.attr("class", "bar")
.attr("x", function(d) { return x(d.step); })
where the x(d.step) is responsible for the distance, the x is set at the var x = ...
Somehow I need to change this, but cant figure it out.
The distance is a bit different since I changed this:
var x = d3.scale.ordinal()
.rangeRoundBands([0, width], .1);
to this:
var x = d3.scale.ordinal()
.rangeRoundBands([0, width], .0);
but it doesn't help much.
Can you help out here?
This is my code:
$('#chartDiv').html('');
var margin = {top: 10, right: 10, bottom: 35, left: 50},
width = 600 - margin.left - margin.right,
height = 250 - margin.top - margin.bottom;
var x = d3.scale.ordinal()
.rangeRoundBands([0, width], .0);
var y = d3.scale.linear()
.range([height, 0]);
var xAxis = d3.svg.axis()
.scale(x)
.orient("bottom");
var yAxis = d3.svg.axis()
.scale(y)
.orient("left")
.ticks(10, "");
var svg = d3.select("#chartDiv").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 + ")");
graphObj.forEach(function(d) {
d.step = +d.step;
d.temp = +d.temp;
});
x.domain(graphObj.map(function(d) { return d.step; }));
y.domain([0, d3.max(graphObj, function(d) { return d.temp; })]);
svg.append("g")
.attr("class", "x axis")
.attr("transform", "translate(0," + height + ")")
.call(xAxis);
svg.append("g")
.attr("class", "y axis")
.call(yAxis)
.append("text")
.attr("transform", "rotate(-90)")
.attr("y", 6)
.attr("dy", "-40px")
.style("text-anchor", "end")
.text("Temperature");
svg.selectAll(".bar")
.data(graphObj)
.enter().append("rect")
.attr("class", "bar")
.attr("x", function(d) { console.log(d.step, x.rangeBand(), x(d.step)); return x(d.step); })
.attr("width", x.rangeBand())
.attr("y", function(d) { return y(d.temp); })
.attr("height", function(d) { return height - y(d.temp); });
if ($('#chartDiv').css('left').replace('px','') < 0) {
$('#chartDiv').animate({
left: 10
}, 1000);
}
you need to add the i variable to the .attr("x", function(d) { return x(d.step); }), like so: .attr("x", function(d, i) { return x.rangeRoundBands() * i; }), so it will go through the bars and place them one after the other (this might need some tweaking, can't do it properly without a jsfiddle) but should at least get you on the path of fixing it without issues