Reputation:
I'm making a horizontal bar chart with d3.js., and I can't change the size of the bar chart rectangle. They're too big for what I want to do. Here's a screenshot because JSFiddle won't show the chart (the data is on my local drive). Here's my code:
var m = [40, 20, 10, 145], //TRBL
w = 400 - m[1] - m[3], //margin.right - margin.left
h = 400 - m[0] - m[2]; //margin.top - margin.bottom
var format = d3.format(",.0f");
var x = d3.scale.linear().range([0, w]),
y = d3.scale.ordinal().rangeRoundBands([0, h], .2);
var xAxis = d3.svg.axis().scale(x).orient("top").tickSize(-10),
yAxis = d3.svg.axis().scale(y).orient("left").tickSize(0);
var cause = d3.select("#cause").append("svg")
.attr("width", w + m[1] + m[3])
.attr("height", h + m[0] + m[2])
.append("g")
.attr("transform", "translate(" + m[3] + "," + m[0] + ")")
d3.csv("data/cause.csv", function(data) {
// Parse numbers, and sort by value.
data.forEach(function(d) { d.number = +d.number; });
data.sort(function(a, b) { return b.number - a.number; });
// Set the scale domain.
x.domain([0, 350]);
y.domain(data.map(function(d) { return d.cause; }));
var bar = cause.selectAll("g.bar")
.data(data)
.enter().append("g")
.attr("class", "bar")
.attr("transform", function(d) { return "translate(0," + y(d.cause) + ")"; });
bar.append("rect")
.attr("width", function(d) { return x(d.number); })
.attr("height", y.rangeBand());
bar.append("text")
.attr("class", "number")
.attr("x", function(d) { return x(d.number); })
.attr("y", y.rangeBand() / 2)
.attr("dx", 3) //Number position
.attr("dy", ".35em") //Position in the rect
.attr("text-anchor", "start")
.text(function(d) { return format(d.number); });
cause.append("g")
.attr("class", "x axis")
.call(xAxis);
cause.append("g")
.attr("class", "y axis")
.call(yAxis);
cause.append("text") //Y AXIS TEXT
.attr("class", "y label")
.attr("x", w / 3)
.attr("dy", "-1.5em")
.text("Cause of Deaths")
.style("font-size","13px");
});
I'm a d3 noobie. Please let me know if there's anything else that's wonky.
Upvotes: 2
Views: 4525
Reputation: 21
var x = d3.scale.linear().range([0, w]),
y = d3.scale.ordinal().rangeRoundBands([0, h], .2);
Just Change
y = d3.scale.ordinal().rangeRoundBands([0, h], .2);
as
// or
y = d3.scale.ordinal().rangeRoundBands([0, h], .5);
// or
y = d3.scale.ordinal().rangeRoundBands([0, h], .6);
According to your choice.
Upvotes: 0
Reputation: 8150
It looks like you want to change the h
variable, right?
It's being used here:
bar.append("rect")
.attr("width", function(d) { return x(d.number); })
.attr("height", y.rangeBand());
To define the height of each bar.
So where it says:
var m = [40, 20, 10, 145], //TRBL
w = 400 - m[1] - m[3], //margin.right - margin.left
h = 400 - m[0] - m[2]; //margin.top - margin.bottom
Change the 400
value to something smaller. It will also be factored into your y
value.
Upvotes: 1