酒吧的高度太大

时间:2016-05-03 10:50:38

标签: javascript css d3.js

我正在实施d3图表,但是我的图表的条形图越过y轴意味着它们已经离开我的画布。看起来高度是问题所在。不知道原因。如果任何值大于500,我的y轴比例将达到500,然后超出我的画布。但规模是由d3制定的。所以我不能操纵比例。这是我的HTML

#include <iostream>

template <typename ...Args>
void apply(const char* fmtString, const Args&... args)
{
    char output[512];
    snprintf(output, 512, fmtString, args...);

    std::cout << output << std::endl;
}

template <typename F, typename ...Args>
struct ReverseAndApply;

template <typename F>
struct ReverseAndApply<F>
{
    template <typename ... AlreadyReversed>
    static void doIt(F func, AlreadyReversed&& ... args)
    {
        func(args...);
    }
};

template <typename F, typename FirstArg, typename ...RestArgs>
struct ReverseAndApply<F, FirstArg, RestArgs...>
{
    template <typename ... AlreadyReversed>
    static void doIt(F func, FirstArg&& arg, RestArgs&& ... restArgs, AlreadyReversed&& ... revArgs)
    {
        ReverseAndApply<F, RestArgs...>::doIt(func, std::forward<RestArgs>(restArgs)..., std::forward<FirstArg>(arg), std::forward<AlreadyReversed>(revArgs)...);
    }
};

template <typename F, typename... Args>
void reverse_and_apply(F func, Args&&... args)
{
    ReverseAndApply<F, Args...>::doIt(func, std::forward<Args>(args)...);
}

int main()
{
    reverse_and_apply(apply<double, const char*, int>, 1, (const char*)"abc", 2.0, "%f %s %d");
    return 0;
}

我的javascript

<!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>

我的json

    $(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);

                    });

                });
 }
    });
});

1 个答案:

答案 0 :(得分: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/