Skip to content

Instantly share code, notes, and snippets.

@fangzhzh
Created March 25, 2014 04:11
Show Gist options
  • Save fangzhzh/9755118 to your computer and use it in GitHub Desktop.
Save fangzhzh/9755118 to your computer and use it in GitHub Desktop.
d3.js 绘制线图
var svg = d3.select("d3_chart");
var data = [4, 8, 15, 16, 23, 42];
var width = 420, barHeight = 20;
var svg = d3.select("d3_chart").append("svg:svg")
.attr("width", width)
.attr("height", barHeight);
var gradient = svg.append("svg:defs")
.append("svg:linearGradient")
.attr("id", "gradient")
.attr("x1", "0%")
.attr("y1", "0%")
.attr("x2", "100%")
.attr("y2", "100%")
.attr("spreadMethod", "pad");
gradient.append("svg:stop")
.attr("offset", "0%")
.attr("stop-color", "#0c0")
.attr("stop-opacity", 1);
gradient.append("svg:stop")
.attr("offset", "100%")
.attr("stop-color", "#c00")
.attr("stop-opacity", 1);
var x = d3.scale.linear()
.domain([0, d3.max(data)])
.range([0, width]);
var chart = d3.select(".chart")
.attr("width", width)
.attr("height", barHeight * data.length);
var bar = chart.selectAll("g")
.data(data)
.enter().append("g")
.attr("transform", function(d, i) { return "translate(0," + i * barHeight + ")"; });
bar.append("rect")
.attr("width", x)
.attr("height", barHeight - 1)
.style("fill", "url(#gradient)");
bar.append("text")
.attr("x", function(d) { return x(d) - 3; })
.attr("y", barHeight / 2)
.attr("dy", ".35em")
.text(function(d) { return d; });
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment