在d3的条形图上绘制元素

时间:2017-04-18 18:11:22

标签: javascript d3.js

您好我尝试创建一个直方图,该图表包含多年的数组,然后绘制它们的频率。现在这是绘制图表的轴而不是实际的条形图,我不知道为什么。

// Check if the form was submitted
if( 'POST' == $_SERVER['REQUEST_METHOD'] && !empty( $_POST['action'] )) {

// Do some minor form validation to make sure there is content
if (isset ($_POST['title'])) { 
    $title =  $_POST['title'];

} else { 
    echo 'Please enter a title';
}
if (isset ($_POST['description'])) { 
    $description = $_POST['description']; 
} else { 
    echo 'Please enter the content'; 
}

$custom_field_1 = $_POST['custom_1'];

// Add the content of the form to $post as an array
$post = array(
    'post_title'    => $title,
    'post_content'  => $description,
    'post_category' => array($_POST['cat']),

    'post_status'   => 'publish',         // Choose: publish, preview, future, etc.
    'post_type'     => 'work'  // Use a custom post type if you want to
);
$pid = wp_insert_post($post);  // Pass  the value of $post to WordPress the insert function    

if ( $_FILES ) {
    $files = $_FILES['upload_attachment'];
    foreach ($files['name'] as $key => $value) {
        if ($files['name'][$key]) {
            $file = array(
                'name'     => $files['name'][$key],
                'type'     => $files['type'][$key],
                'tmp_name' => $files['tmp_name'][$key],
                'error'    => $files['error'][$key],
                'size'     => $files['size'][$key]
            );

            $_FILES = array("upload_attachment" => $file);

            foreach ($_FILES as $file => $array) {
                $newupload = insert_attachment($file,$pid);
            }
        }
    }
}
$category_filter = array($_POST['cat_filter']);

1 个答案:

答案 0 :(得分:0)

您有几个错误:

  1. rect元素里面没有内容,所以这部分是错误的

    bar.append("rect").attr("x", 1)
                            .attr("width", barWidth)
                            .attr("height", function(d) { return maxBarHeight - d.length;  });
    
    
    
    
     bar.append("text")
            .attr("class", "axis-label")
            .attr("dy", "-.75em")
            .attr("y", 6)
            .attr("x", barWidth / 2)
            .attr("text-anchor", "middle")
            .text(function(d) { return formatCount(d.length); });
    
  2. 条形图实际上正在绘制,但是当我检查它时,您为d.x1位置指定了x,这超过了2000,因此条形图在页面外绘制(您可以检查它来自铬)

    .attr("x", function(d) { console.log("X" + d.x1);return d.x1; })

    相反应该使用scale,你已经声明过,所以 .attr("x", function(d) { console.log("X" + d.x1);return x(d.x1); })

  3. 我已经更改了这两个项目,并准备了可以运行的代码段 并继续在这里工作

      <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Title</title>
    </head>
    <body>
    <div id="chart"></div>
    
    <script src="http://d3js.org/d3.v4.min.js" charset="utf-8"></script>
      <script>
      
        var data1 = [2000, 2001, 2012,2013,2013,2014];
        d3  .select('#chart')
            .datum(data1)
            .call(histogramChart()
                .width(700)
                .height(250)
                .lowerBand(2000)
                .upperBand(2016)
                .bins(17)
                .yAxisLabel("# of Organizations")
                .xAxisLabel("Year")
            );
        function histogramChart(){
            var margin = {
                top: 64,
                right: 32,
                bottom: 72,
                left: 32,
                labels: 32
            };
            //defaults
            var height = 200;
            var width = 500;
            var lowerBand = 2000;
            var upperBand = 2017;
            var bins = 17;
            var chartTitle = ["Selected Partner Organizations Per Year"];
            var yAxisLabel = "y axis label";
            var xAxisLabel = "x axis label";
            var xformat = function(d){return d};
            var formatCount = d3.format(",.0f");
            function chart(selection) {
                var maxBarHeight = height - (margin.top + margin.bottom);
                var chartWidth = width - margin.right - margin.left;
                selection.selectAll('svg').remove();//remove old charts
                selection.each(function(values) {
                    var x = d3.scaleLinear()
                        .domain([lowerBand, upperBand])
                        .range([margin.labels, chartWidth]);
                    // Generate a histogram using XX bins.
                    var data = d3.histogram()
                        .thresholds(x.ticks(bins))
                        (values);
                    //fill the chart width, with 1px spacing between
                    var numBins = data.length;
                    var barWidth = parseInt((chartWidth-margin.labels)/numBins) - 1;
                    var y = d3.scaleLinear()
                        .domain([0, d3.max(data, function(d) { return d.length; })])
                        .range([maxBarHeight, 0]);
                    var xAxis = d3.axisBottom()
                        .scale(x)
                        .tickFormat(xformat);
                    var svgContainer = d3.select(this).append("svg")
                        .attr("class", "chart mini-column-chart")
                        .attr("width", width)
                        .attr("height", height)
                        .append("g")
                        .attr("transform", "translate(" + margin.left + "," + margin.top + ")");
                    var bar = svgContainer.selectAll("rect")
                        .data(data)
                        .enter().append("rect")
                        .attr("class", "bar")
                        .attr("x", function(d) { console.log("X" + d.x1);return x(d.x1); })
                        .attr("y", function(d) { console.log("lenth" + d.length);return d.length; })
                    .attr('stroke','white')
                        .attr("width", barWidth)
                        .attr("height", function(d) { console.log(maxBarHeight - d.length );return maxBarHeight - d.length; });
    /*
                    svg.selectAll("rect")
                        .attr("x", 1)
                        .attr("transform", function(d) {
                            return "translate(" + x(d.x0) + "," + y(d.length) + ")"; })
                        .attr("width", function(d) { return x(d.x1) - x(d.x0) -1 ; })
                        .attr("height", function(d) { return height - y(d.length); });
                    */
                    console.log("max: " + maxBarHeight);
                    var xAxisG = svgContainer.append("g")
                        .attr("class", "x axis")
                        .attr("transform", "translate( 0," + (height - margin.top - margin.bottom) + ")")
                        .call(xAxis);
                    var header = svgContainer.append("text")
                        .attr("class", "chart-title")
                        .attr("x", width/2)
                        .attr("text-anchor", "middle")
                        .attr("dy", -32)
                        .text(chartTitle);
                  /*
                    bar.append("rect")
                        .attr("x", 1)
                        .attr("width", barWidth)
                        .attr("height", function(d) { return maxBarHeight - d.length; });
                    bar.append("text")
                        .attr("class", "axis-label")
                        .attr("dy", "-.75em")
                        .attr("y", 6)
                        .attr("x", barWidth / 2)
                        .attr("text-anchor", "middle")
                        .text(function(d) { return formatCount(d.length); });
                        */
                    xAxisG.append("text")
                        .attr("class", "axis-label")
                        .attr("x", margin.left)
                        .attr("dy", 56)
                        .text(xAxisLabel);
                    svgContainer.append("g")
                        .attr("class", "y axis")
                        .append("text")
                        .attr("class", "axis-label")
                        .attr("transform", "rotate(-90)")
                        .attr("y", 8)
                        .attr("x", -(height-margin.top-margin.bottom))
                        .style("text-anchor", "start")
                        .text(yAxisLabel);
                });
            }
            chart.title = function(_) {
                if (!arguments.length) return chartTitle;
                chartTitle = _;
                return chart;
            };
            chart.lowerBand = function(_) {
                if (!arguments.length) return lowerBand;
                lowerBand = _;
                return chart;
            };
            chart.upperBand = function(_) {
                if (!arguments.length) return upperBand;
                upperBand = _;
                return chart;
            };
            chart.width = function(_) {
                if (!arguments.length) return width;
                width = _;
                return chart;
            };
            chart.height = function(_) {
                if (!arguments.length) return height;
                height = _;
                return chart;
            };
            chart.bins = function(_) {
                if (!arguments.length) return bins;
                bins = _;
                return chart;
            };
            chart.xformat = function(_) {
                if (!arguments.length) return xformat;
                xformat = _;
                return chart;
            };
            chart.yAxisLabel = function(_) {
                if (!arguments.length) return yAxisLabel;
                yAxisLabel = _;
                return chart;
            };
            chart.xAxisLabel = function(_) {
                if (!arguments.length) return xAxisLabel;
                xAxisLabel = _;
                return chart;
            };
            chart.focusLabel = function(_) {
                if (!arguments.length) return focusLabel;
                focusLabel = _;
                return chart;
            };
            chart.focusValue = function(_) {
                if (!arguments.length) return focusValue;
                focusValue = _;
                return chart;
            };
            return chart;
        }
      </script>
    </body>
    </html>