简体   繁体   English

D3条形图故障排除

[英]D3 Bar Chart Troubleshooting

I have a database with 5 columns, ID, customerName, dateYear, dateMonth, and dateDay. 我有一个包含5列的数据库,ID,customerName,dateYear,dateMonth和dateDay。 The date columns are added into the database when the user sends the form. 用户发送表单时,日期列将添加到数据库中。 So for example if a user sent the form today the 3 columns would have 2016, June, and 7. I want to make a D3 bar chart that can pull this information and display how many forms were sent each month/year. 因此,例如,如果用户今天发送表单,则3列将分别是2016年,6月和7。我想制作一个D3条形图,以提取此信息并显示每月/每年发送的表单数量。 I have a list of checkboxes in HTML for the admin to select one or more months, and a year. 我有一个HTML复选框列表,供管理员选择一个或多个月和一年。

        <input type="submit" name="monthlyReport" value="Generate a Monthly Report for:" />
        <br>
        <input type="checkbox" value="January" name="monthList[]"/>January
        <br>
        <input type="checkbox" value="February" name="monthList[]"/>February

etc... 等等...

<select name="selyear1">
    <option value="2016">2016</option>
    <option value="2017">2017</option>
    <option value="2018">2018</option>
    <option value="2019">2019</option>
    <option value="2020">2020</option>
</select>

Here is my PHP code that takes the user input and turns it into a query: 这是我的PHP代码,它接受用户输入并将其转换为查询:

$monthList = array("January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December");
$yearList = array("2016", "2017", "2018", "2019", "2020");

$monthlyReport = isset($_POST["monthlyReport"]) ? $_POST["monthlyReport"] : "";
$monthList = array();
$monthList = isset($_POST["monthList"]) ? $_POST["monthList"] : "";
$selectedYear = isset($_POST["selyear1"]) ? $_POST["selyear1"] : "";
if(isset($monthlyReport) && !empty($monthList) && in_array($selectedYear, $yearList)) {
    foreach ($monthList as $month){ 
        if (in_array($month, $monthList)) {

            $stmt = $conn->prepare("SELECT dateYear, dateMonth FROM just_ink WHERE dateMonth = :month AND dateYear= :year");
            $stmt->execute(array(":month" => $month, ":year"=> $selectedYear));
            $result[] = $stmt->fetchAll(PDO::FETCH_ASSOC);

        }
    }
}
var_dump($result);

$result will dump this: $ result将转储此内容:

array(2) { [0]=> array(1) { [0]=> array(2) { ["dateYear"]=> string(4) "2016" ["dateMonth"]=> string(7) "January" } } [1]=> array(2) { [0]=> array(2) { ["dateYear"]=> string(4) "2016" ["dateMonth"]=> string(4) "June" } [1]=> array(2) { ["dateYear"]=> string(4) "2016" ["dateMonth"]=> string(4) "June" } } }

So how exactly do I turn this result into the D3 bar chart? 那么,如何准确地将此结果转换为D3条形图? I've look at the d3Noob tips and tricks but this is a more advanced case I believe. 我已经看过d3Noob的技巧和窍门,但是我相信这是一个更高级的案例。 Thanks ahead of time for the responses! 提前感谢您的答复!

If I understand correctly you create an array with the desired values. 如果我理解正确,则可以创建具有所需值的数组。

$array = array( array("2016", "January"),
                array("2016", "February"),
                array("2016", "February"),
                array("2016", "February"),
                array("2016", "March"),
                array("2016", "March"),
                array("2016", "June"),
                array("2016", "June")
              );

echo json_encode($array);
//[["2016","January"],["2016","February"],["2016","February"],["2016","February"],["2016","March"],["2016","March"],["2016","June"],["2016","June"]]

I would expose an endpoint which would return this json and then use it within my script, so you may be able to make an async call and don't stop the rendering of your page in order to fetch/wait for data. 我将公开一个端点,该端点将返回此json ,然后在我的脚本中使用它,因此您可以进行异步调用,而不必停止页面的呈现以获取/等待数据。

If we use the json returned by the previous snippet we can call d3.json and modify the data in order to create a bar chart. 如果我们使用上一个代码片段返回的json,则可以调用d3.json并修改数据以创建条形图。

d3.json("data.json", function(error, data) {
  var nested_data = d3.nest()
    .key(function(d) {
      return d[1];
    })
    .rollup(function(leaves) {
      return leaves.length;
    })
    .entries(data);
    console.log(nested_data);
    //Object {key: "January", values: 1}
    //Object {key: "February", values: 3}
    //Object {key: "March", values: 2}
    //Object {key: "June", values: 2}


  x.domain(nested_data.map(function(d) { // Set x domain by keys (Month Name)
    return d.key;
  }));
  y.domain([0, d3.max(nested_data, function(d) { // Set y domain by finding max value (Month count)
    return d.values;
  })]);

  svg.append("g") // Append x-axis
    .attr("class", "x axis")
    .attr("transform", "translate(0," + height + ")")
    .call(xAxis);

  svg.append("g") // Append y-axis
    .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") // Join our data
    .data(nested_data) 
    .enter() // For each value do the following
    .append("rect") 
    .attr("class", "bar")
    .attr("x", function(d) {
      return x(d.key);
    })
    .attr("width", x.rangeBand())
    .attr("y", function(d) {
      return y(d.values);
    })
    .attr("height", function(d) {
      return height - y(d.values);
    });
}

You can find a working plnkr with the code here: http://plnkr.co/edit/Jin12g7dVdCq2eu46FnX?p=preview 您可以在此处找到具有代码的工作plnkr: http ://plnkr.co/edit/Jin12g7dVdCq2eu46FnX?p=preview

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM