2016-02-20 208 views

回答

0

可能你可以使用c3.js这是一个基于D3的可重用图表库。

这里是你正在寻找一个例子: Combination Chart

你可以结合“酒吧”,“花”,“行”,“区域”等。

0

你首先需要做这样的选择框:

<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

希望这有助于!