D3 Novice, problem in displaying text in SVG

2,782 views
Skip to first unread message

simarj...@gmail.com

unread,
Jan 10, 2012, 11:53:31 PM1/10/12
to d3-js
Hi

I am a D3.js starter going through Mike Bostock's tutorial 'A Bar
Chart, Part 1'.
I have put the whole code below. Specifically I am unable to show text
on the SVG rectangles.
I feel the issue is in this piece:

chart1.selectAll("text")
.data(data1)
.enter().append("svg:text")
.attr("x",x1)
.attr("y", function(d) { return y(d) + y.rangeBand() / 2; })
.attr("dx", -10) // padding-right
.attr("dy", ".35em") // vertical-align: middle
.attr("text-anchor", "end") // text-align: right
.attr("text",String);

but having followed Mike's code to the hilt, can't really make out
what's wrong with it. Will appreciate your help on this.

Thanks
Simarjeet

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://
www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />


<style type="text/css">
.chart div {
font: 10px san-serif;
background-color: steelblue;
text-align: right;
padding: 3px;
margin:1px;
color: white;
}

.chart1 rect {
stroke: white;
fill: steelblue;
}

.chart1 text {

fill: #000000;
}



</style>

<title>Bar Graphs</title>
<script type="text/javascript" src="http://mbostock.github.com/d3/
d3.js"></script>
</head>

<body>
<script type= "text/javascript" >

var data1 = [4,8,15,16,23,42];
var chart = d3.select("body").append("div")
.attr("class", "chart");

var x = d3.scale.linear().domain([0,
d3.max(data1)]).range(["0px","420px"]);

chart.selectAll("div")
.data(data1)
.enter().append("div")
.style("width", x)
.text(String);


var y = d3.scale.ordinal()
.domain(data1)
.rangeBands([0,120]);

var chart1 = d3.select("body").append("svg")
.attr("class", "chart1")
.attr("width", 420)
.attr("height", 20*(data1.length));

var x1 = d3.scale.linear().domain([0,
d3.max(data1)]).range(["0","420"]);

chart1.selectAll("rect")
.data(data1)
.enter().append("rect")
.attr("y",y)
.attr("width",x1)
.attr("height",20);


chart1.selectAll("text")
.data(data1)
.enter().append("svg:text")
.attr("x",x1)
.attr("y", function(d) { return y(d) + y.rangeBand() / 2; })
.attr("dx", -10) // padding-right
.attr("dy", ".35em") // vertical-align: middle
.attr("text-anchor", "end") // text-align: right
.attr("text",String);

</script>

<svg xmlns="http://www.w3.org/2000/svg" version="1.1">
</svg>

</body>

</html>

Mike Bostock

unread,
Jan 11, 2012, 12:04:21 AM1/11/12
to d3...@googlegroups.com
> .attr("text",String);

This should be .text(String). You want to set the text content, not
add an attribute named "text".

Mike

simarj...@gmail.com

unread,
Jan 11, 2012, 12:08:01 AM1/11/12
to d3-js
Thanks Mike!
How could I do that :)
Reply all
Reply to author
Forward
0 new messages