questing
questing

Reputation: 172

Can't display a single bar in D3

I'm trying to display single bars in D3. I have a data of the type:

data = [
  "value1": 1,
  "value2": 2,
  "value3": 3,
]

Because the y scale is not the same, I'm trying to display three different bar-charts, each one of them just with a bar. I don't need x-axis.

As you can see in this fiddle: http://jsfiddle.net/GPk7s/, The bar is not showing up, although if you inspect the source code, it has been added. I think it is because I'm not providing a x range, but I don't know how, because I don't really have one.

I just want a bar whose height is related to the range I provide (in the fiddle example this is [10, 30]).

I copy here the code just in case:

var margin = {
top: 50,
right: 0,
bottom: 100,
left: 30
},
width = 200 - margin.left - margin.right,
height = 200 - margin.top - margin.bottom;

var data = [{ "Value": 22.5 } ];

var yRange = d3.scale.linear().range([height, 0]);
yRange.domain([10, 30]);

var svg = d3.select("#chart").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 + ")");

svg.selectAll("rect")
.data(data)
.enter()
.append("rect")
.attr("class", "bar")
.attr("y", function (d) {
return yRange(d.Value);
})
.attr("height", function (d) {
return height - yRange(d.Value);
})
.attr("y", function (d) {
return yRange(d.Value) + 3;
})
.attr("dy", ".75em")
.text(function (d) {
return d.Value;
});

Thanks for your help!

Upvotes: 0

Views: 639

Answers (1)

ckersch
ckersch

Reputation: 7687

There are two problems with what you are doing:

1) Your rectangle doesn't have a width. I added this:

...
.attr("class", "bar")
.attr("width", 10)
.attr("y", function (d) {
...

2) Your data is not an array. D3 expects arrays of data to be provided with the .data() method, and you have data = {Value : 22.5} (effectively). I changed it to this:

...
var data = [{'Value' : 22.5}];
...

Updated fiddle is here.

Upvotes: 1

Related Questions