我在条形图工作:http://bl.ocks.org/Caged/6476579在d3.jsd3.js折线图与条形图
我想有说条形图的组合,并添加一行图表相同的数据。
bl.ocks中的所有线图示例都有很大不同。
我该如何做到这一点?
我在条形图工作:http://bl.ocks.org/Caged/6476579在d3.jsd3.js折线图与条形图
我想有说条形图的组合,并添加一行图表相同的数据。
bl.ocks中的所有线图示例都有很大不同。
我该如何做到这一点?
你首先需要做这样的选择框:
<select>
<option id="bar">bar</option>
<option selected="selected" id="line">line</option>
</select>
做一个功能,使AJAX并根据选择的选项加载图:
function getMyData() {
d3.tsv("data.tsv", type, function(error, data) {
x.domain(data.map(function(d) {
return d.letter;
}));
y.domain([0, d3.max(data, function(d) {
return d.frequency;
})]);
//check select for the option
if (d3.select("select").node().value == "line") {
showLineChart(data);//make line chart
} else {
showBarChart(data);//make bar chart
}
});
}
功能,使线图表:
function showLineChart(data) {
svg.selectAll("*").remove();
svg.append("g")
.attr("class", "x axis")
.attr("transform", "translate(0," + height + ")")
.call(xAxis);
svg.append("g")
.attr("class", "y axis")
.call(yAxis)
.append("text")
.attr("transform", "rotate(-90)")
.attr("y", 6)
.attr("dy", ".71em")
.style("text-anchor", "end")
.text("Frequency");
svg.append("path")
.datum(data)
.attr("class", "line")
.attr("d", line);
}
的功能,使条形图:
function showBarChart(data) {
svg.selectAll("*").remove();
svg.append("g")
.attr("class", "x axis")
.attr("transform", "translate(0," + height + ")")
.call(xAxis);
svg.append("g")
.attr("class", "y axis")
.call(yAxis)
.append("text")
.attr("transform", "rotate(-90)")
.attr("y", 6)
.attr("dy", ".71em")
.style("text-anchor", "end")
.text("Frequency");
svg.selectAll(".bar")
.data(data)
.enter().append("rect")
.attr("class", "bar")
.attr("x", function(d) {
return x(d.letter);
})
.attr("width", x.rangeBand())
.attr("y", function(d) {
return y(d.frequency);
})
.attr("height", function(d) {
return height - y(d.frequency);
})
.on('mouseover', tip.show)
.on('mouseout', tip.hide)
}
工作代码here
希望这有助于!