I am new to D3 and I have written the following script to display bar charts. But , I need to do three more things
1) Get a dashed line on Y-axis
2) Increase spacing between the graphs
3) Display Value beside the end of the bar graph
Here is my code below -
<!DOCTYPE html>
<meta charset="utf-8">
<style>
.chart div {
font: 10px sans-serif;
background-color: steelblue;
text-align: right;
padding: 3px;
margin: 1px;
color: white;
}
</style>
<div class="chart"></div>
<script src="//d3js.org/d3.v3.min.js"></script>
<script>
//var data = [4, 8, 15, 16, 23, 42];
var data = [ {
"label" : "You ",
"value" : 60
}, {
"label" : " Recommended",
"value" : 60
}, {
"label" : "Peers",
"value" : 40
} ];
var color = d3.scale.ordinal().range(
[ "#8BA870", "#000000", "#FF8040", "#ff8c00" ]);
var barPad = 10;
// var x = d3.scale.linear().domain([ 0, d3.max(data)]).range([ 0, 420 ]);
var x = d3.scale.linear().domain([0, 1000]).range([0, 1000]);
d3.select(".chart").selectAll("div").data(data).enter().append("div")
.style({stroke: "black", "stroke-width": "2px"})
.style("height", function(d) { return 20+"px"; })
.style("font-size","20px")
.style("width", function(d) {
return (d.value+100) + "px";
}).style("background-color", function(d, i) {
return color(i);
}).text(function(d, i) {
return data[i].label;
});
</script>
You can do something like this:
for making the y axis
d3.select(".chart").selectAll("div").data(data).enter()
.append("div")
.style("width","1px")
.style("height",height*2 + "px")
.style("padding-top","0.1px")
.style("padding","0.1px")
.style("background-color","black")
for making bars
.append("div")
.style({stroke: "black", "stroke-width": "2px"})
.style("height", function(d) { return height+"px"; })
.style("font-size","20px")
.style("margin-top","10px")
.style("text-align","left")
.style("width", function(d) {
return (d.value+100) + "px";
}).style("background-color", function(d, i) {
return color(i);
}).text(function(d, i) {
return data[i].label;
})
For making text @ the end of bar:
.append("p")
.style("margin-top", function(d) {
return -height -5 + "px";
})
.style("margin-left", function(d) {
return (d.value+100) +10 + "px";
})
.style("color","black")
.text(function(d){ return d.value});
working code here
Stroke width for dashed lines
svg.append("path")
.datum(data1)
.attr("class", "line blue")
.attr("stroke-width", "3px")
.attr("d", line1);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.