Сначала нужно сделать выбор коробки, как это:
<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
Надеется, что это помогает!