【问题标题】:Height of bars too large钢筋高度太大
【发布时间】:2016-08-28 09:07:15
【问题描述】:

我正在实现 d3 图表,但图表的条形穿过 y 轴意味着它们超出了我的画布。似乎高度是问题所在。不知道原因。如果任何值大于 500,我的 y 轴比例直到 500,那么它就会超出我的画布。但是刻度是d3制作的。所以我无法操纵比例。这是我的 html

<!doctype html>
<html>

<head>
    <meta charset="UTF-8">
    <meta content="utf-8" http-equiv="encoding">

    <title>D3</title>
    <!-- <link rel="stylesheet" type="text/css" href="mystyle1.css" /> -->

    <style>
        body {
            color: #000;
        }

        .axis {
            font: 10px sans-serif;
        }

        .axis path,
        .axis line {
            fill: none;
            stroke: #000;
            shape-rendering: crispEdges;
        }

        .bar {
            fill: steelblue;
        }

        .bar:hover {
            fill: brown;
        }
    </style>

    <script type="text/javascript" src="http://mbostock.github.com/d3/d3.js"></script>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js"></script>
    <script src="123.js" type="text/javascript"></script>

<script>
 var thisIsGlobal;
 </script>

</head>
<script src="http://d3js.org/d3.v3.min.js"></script>

<body>
<div id="chart"></div>
<div align="center">
    From : <input type="date" name="field1" id="field1" /> To : <input type="date" name="field2" id="field2" /><br /><br />
    <input type="button" onclick="render(true)" value="Submit" />
</div>

<script>
    var jsonURL = 'avb.json';

    var myData = [];
    var fliterdata=[];
    var tempdata=[];
    var selectop="";

function filterJSON(json, key, value) {
   var result = [];
  for (var foo in json) {

    if (json[foo][key] == value) {
      result.push(json[foo]);


    }
  }
  return result;
}

function selectValue(d){
   // console.log("before op",selectop );
  switch(selectop){
            case "01":
                return d.val001;
                break;
            case "02":
                return d.val002;
                break;
            case "03":
                return d.val003;
                break;
            case "04":
                return d.val004;
                break;
            case "05":
                return d.val005;
                break;
            default:
                //console.log("default");
                return d.val001;
        }


 }

    var margin = {
        top: 20,
        right: 0,
        bottom: 80,
        left: 40
    };
    var width = 500 - margin.left - margin.right;
    var height = 300 - margin.top - margin.bottom;



    var xScale = d3.scale.ordinal().rangeRoundBands([0, width], .1);
    var yScale = d3.scale.linear().range([height, 0]);
    var hAxis = d3.svg.axis().scale(xScale).orient('bottom').tickFormat(d3.time.format("%Y-%m-%d"));
    var vAxis = d3.svg.axis().scale(yScale).orient('left');
    var tooltip = d3.select('body').append('div')
            .style('position', 'absolute')
            .style('background', '#f4f4f4')
            .style('padding', '5 15px')
            .style('border', '1px #333 solid')
            .style('border-radius', '5px')
            .style('opacity', 'o');

//function getDates() {
  //      return [document.getElementById('field1').value, document.getElementById('field2').value];
  //  }

    function render(filterByDates) {


        d3.select('svg').remove();

        if (filterByDates) {

                tempData=fliterdata;
                console.log("before date fliter data", tempData);
            var date1 = new Date(document.getElementById('field1').value);
            var date2 = new Date(document.getElementById('field2').value);

            //date1 = new Date(date1 + " UTC");
            //date2 = new Date(date2 + " UTC");

            //date1 = new Date( date1.getTime() + (date1.getTimezoneOffset() * 60000));
            //date2 = new Date( date2.getTime() + (date2.getTimezoneOffset() * 60000));


            tempData = tempData.filter(function(d) {
                console.log(date1,date2);
              //  alert(date1);
                return d.date >= date1 && d.date <= date2;


            });
                console.log("After date fliter data", tempData);
        }


        xScale.domain(tempData.map(function(d) {
                    return d.date;
                }).sort(function(a,b) {
                  return a > b;
                })
        );

        yScale.domain([0, d3.max(tempData, function(d) {
                //console.log("selectValue(d)"  , selectValue(d));
                //var cool=d.val00+selectop;
                //console.log("cool",cool);
            return selectValue(d);
        })]);

        var svg = d3.select('#chart').append('svg')
               .attr("width", width + margin.left + margin.right)
               .attr("height", height + margin.top + margin.bottom)
                .append("g")
               .attr("transform", "translate(" + margin.left + "," + margin.top + ")");

        svg


                .append('g')
                .attr("class", "x axis")
                .attr("transform", "translate(0," + height + ")")
                .call(hAxis)
                .selectAll("text")
                .style("text-anchor", "end")
                .attr("dx", "-.8em")
                .attr("dy", "-.55em")
                .attr("transform", "rotate(-90)");

        svg
                .append('g')
                .attr("class", "yaxis")
                .call(vAxis)

        svg
                .selectAll(".bar") //makes bar
                .data(tempData)
                .enter().append("rect")
                .attr("class", "bar")
                .style("fill", "teal")
                .attr("x", function(d) {
                    return xScale(d.date);
                })
                .attr("width", xScale.rangeBand())
                .attr("y", function(d) {


                    return yScale(selectValue(d));
                })
                .attr("height", function(d) {

                    console.log("as", d.value);
                    return height - yScale(selectValue(d));
                })
                .on('mouseover', function(d) {
                    tooltip.transition()
                            .style('opacity', 1)

                    tooltip.html(d.value)
                            .style('left', (d3.event.pageX) + 'px')
                            .style('top', (d3.event.pagey) + 'px')
                    d3.select(this).style('opacity', 0.5)
                })
                .on('mouseout', function(d) {
                    tooltip.transition()
                            .style('opacity', 0)
                    d3.select(this).style('opacity', 1)
                });
    }

    d3.json(jsonURL, function(data) {

        myData = data;
        myData.forEach(function(d) {

            d.date = new Date(d.date);
            d.value="";

            d.name = +d.name;
            console.log(d.date,"Gt date");
            d.date = new Date(d.date + " UTC");
            console.log(d.date,"localtimezone date");
        });

        //myData.data.sort();
        //console.log(,"hello j");

        //render(false,myData);
       // console.log(render);
        //copy from here 

        //tempData=myData;


         $("#listbox").on("click", function() {




            var key = $(this).val();

            var value=$('#listbox option:selected').text();
            console.log("tx:", value);

            selectop=String(key);
            selectop=selectop.slice(-2);
             console.log("mydata: ", myData);
             console.log("prod:",selectop );

            fliterdata=filterJSON(myData, key, value);

            console.log("fliterdata: ", fliterdata);
            tempData=fliterdata;
                    render(false);




        });

        //till here
    });
</script>

<label> List of Tables : </label><br>
<form name="myform" id="myForm">
    <div style="height: 30px; width: 50px;">
        <select id="dropdown1"></select>
    </div>
    <style>
        #listbox {
            display: none;
        }
        #listbox {
            position: relative;
        }
    </style>

    <div style="margin-left: 150px; margin-top: -30px; height: auto;">
        <select id="listbox", multiple></select>
    </div>

</form>
</body>
</html>

我的 javascript

    $(document).ready(function() {
        $.ajax({
            url: "avb.json",
            dataType: "json",
            success: function(obj) {
                console.log("obj--", obj)
                var jsObject = obj;
                var usedNames = [];
                $('<option>', {
                    text: 'Select your Option',
                    value: '',
                    selected: 'selected',
                    disabled: 'disabled',
                    location: 'fixed'
                }).appendTo('#dropdown1')
                $.each(obj, function(key, value) {
                    if (usedNames.indexOf(value.name) == -1)  {

                        $("#dropdown1").append("<option value=" + key + ">" + value.name + "</option>");
                        usedNames.push(value.name);
                        }

                });
                $('#dropdown1').change(function() {

                    $('#listbox').toggle(this.value != "");




                });

       $('#dropdown1').change(function() {

                    $('#listbox').empty();

                    $('<option>', {
                        text: 'Select your List Option',
                        value: '',
                        selected: 'selected',
                        disabled: 'disabled'
                    }).appendTo('#listbox');


                    var selection = $('#dropdown1 :selected').text();
                    console.log("as".selection);
                    $.each(jsObject, function(index, value) {
                        console.log("%o",value)
                        if (value['name'] == selection) {
                            var optionHtml = '';
                            for (var i = 1; i <=20; i++) {
                                var attr = 'attr' + ('000' + i).substr(-3);
                                var val = 'val' + ('000' + i).substr(-3);
                                //optionHtml += '<option value="' + attr + '" data-val="'+value[val]+'">' + value[attr] + '</option>';

                                if(value[val]){ optionHtml += '<option value="' + attr + '" data-val="'+value[val]+'">' + value[attr] + '</option>';  }


                            }

                            $("#listbox").css("width", "500px")

                            $("#listbox").css("height", "300px")
                            $('#listbox').append(optionHtml);
                            return false;
                        }
                        var selectedOption = $(this).find('option:selected');
                        console.log(selectedOption);

                    });

                });
 }
    });
});

我的json

[ {
 "name": "ABC",
 "date": 1459461600000, 
"attr001": "SIGN1",
 "val001": "7", 
"attr002": "SIGN2",
 "val002": "7",
 "attr003": "SIGN3", 
"val003": "100.00", 
"attr004": "SIGN4", 
"val004": "0" 
}, 
{
"name": "ABC",
 "date": 1459461600000,
 "attr001": "SIGN1",
 "val001": "20", 
"attr002": "SIGN2", 
"val002": "70", 
"attr003": "SIGN3", 
"val003": "100.00",
 "attr004": "SIGN4",
 "val004": "50" 
 }, 


 { "name": "XYZ", 
"date": 1459125900000, 
"attr001": "VISSE1",
 "val001": "100", 
"attr002": "VISSE2",
 "val002": "7",
 "attr003": "VISSE3",
 "val003": "300.00",
 "attr004": "VISSE4",
 "val004": "0"
 },

 { "name": "XYZ",
 "date": 1459461600000,
 "attr001": "VISSE1", 
"val001": "50", 
"attr002": "VISSE2",
 "val002": "70",
 "attr003": "VISSE3",
 "val003": "300.00",
 "attr004": "VISSE4",
 "val004": "0" },

{ "name": "XYZ", 
"date": 1459461900000, 
"attr001": "VISSE1",
"val001": "300", 
"attr002": "VISSE2",
 "val002": "10", 
"attr003": "VISSE3", 
"val003": "500.00",
 "attr004": "VISSE4",
 "val004": "0" } ]

【问题讨论】:

  • 你能把你的例子放在 jsfiddle 上吗?
  • 这是我的小提琴,但在这个 chrt 中没有得到渲染..不知道为什么
  • 可以链接到 jsfiddle/codepen/etc 上的托管版本,也可以提供相关文件 123.jsavb.json
  • 这不是你的小提琴,因为你不显示你的数据,所以很明显它不会运行。添加您的数据,我们可以查看
  • 这是你的小提琴:jsfiddle.net/thatOneGuy/ru2y41Lo。而在另一个问题上,我帮你解决了这个问题:jsfiddle.net/thatOneGuy/k013yrgc。通过不创建一个工作小提琴,您使自己变得更加困难。在尝试回答您的问题之前,我不会付出更多努力来使您的代码正常工作。在提出问题之前有一个工作示例。否则你不会得到答案!!!!!!

标签: javascript css d3.js


【解决方案1】:

您的问题是您的 d3.max 函数没有返回正确的值。所以代替这个:

d3.max(myData, function(d) {
   console.log(d.val001)
     return d.val001;
   })

这样做:

d3.max(myData, function(d) {
   console.log(d.val001)
     return +d.val001; //this is the change
   })

这是由于您的函数没有将您的字符串转换为整数。

更新小提琴:http://jsfiddle.net/thatOneGuy/k013yrgc/14/

【讨论】:

  • 我在这里更改了代码 yScale.domain([0, d3.max(tempData, function(d) { return selectValue(+d); 但现在我的图表没有显示出来跨度>
  • 什么是'selectValue'?
  • 你到底想用return selectValue(+d); 做什么
  • 你需要这样做return +selectValue( "01");,最好只返回值,即val001而不是d.val001我想你可以弄清楚其余的。
  • 嗨..现在它正在工作,但现在在 y 刻度上是一个点,然后逗号出现在这样的数字之前
猜你喜欢
  • 2016-08-05
  • 2012-06-26
  • 2013-07-27
  • 2012-10-15
  • 2012-04-28
  • 2012-05-24
  • 1970-01-01
  • 2011-11-17
  • 2012-08-06
相关资源
最近更新 更多