繁体   English   中英

D3 Y轴刻度不可见

[英]D3 Y Axis Scale Not Visible

我创建了d3响应式条形图。它在chrome中工作正常,但是当我在Mozilla浏览器中渲染相同的图时,y轴比例不可见。我无法理解他为什么如此行事。下面我也提到了我当前正在使用的脚本:

<script>

jQuery(document).ready(function(){

          //section 3

    function getRatio(side) {
 return (( margin[side] / width ) * 100) + "%";
}
    var margin = { left: 50, top: 10, right: 150, bottom: 30 },
    width  = 700,
    height = 210,
    // marginRatio converts margin absolute values to 
    // percent values to keep SVG responsive
    marginRatio = { 
      left:   getRatio("left"), 
      top:    getRatio("top"), 
      right:  getRatio("right"), 
      bottom: getRatio("bottom")
    };


var legendRectSize = 8;
var legendSpacing = 8;

var x0 = d3.scale.ordinal()
    .rangeRoundBands([0, width], .1);

var x1 = d3.scale.ordinal();

/*var y = d3.scale.linear()
    .range([height, 0]);*/


var color = d3.scale.ordinal()
   .range(["#BF6666","#AEA4A2","#A5735C","#BC957F","#FF9F63","#D0CC96","#BCBC8F"]);



/*var svg = d3.select("#barrchart").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 + ")");*/
var svg = d3.select("div#barrchart")
    // Create div to act as SVG container
    .append("div")
    .attr("id","svg-container")
        // Add SVG that will contain Graph elements
        .append("svg")
        // Add margin to show axes
        .style("padding", marginRatio.top + " " + marginRatio.right +  " " + marginRatio.bottom +  " " + marginRatio.left )


       // Preserve aspect ratio xMinYmin ensures SVG fills #svg-container
        .attr("preserveAspectRatio", "xMinYMin meet")
        // Sets the viewbox, for more info on viewbox, combined with preveserveAspectRatio, this is what turns the bar chart
        // into a responsive bar chart
        .attr("viewBox", "0 0 " + ( width + margin.left + margin.right  )+ " " +( height + margin.top + margin.bottom ) )
        // Id to target with CSS
        .attr("id", "svg-content-responsive");

dataset = [
    {label:"Pending", "a":20, "b":10, "c": 50},
     {label:"InProgress", "a":15, "b":30, "c": 40},
      {label:"Finished", "a":20, "b":25, "c": 20},
      {label:"Deliver", "a":10, "b":35, "c": 40}
];


var options = d3.keys(dataset[0]).filter(function(key) { return key !== "label"; });

dataset.forEach(function(d) {
    d.valores = options.map(function(name) { return {name: name, value: +d[name]}; });
});
var xAxis = d3.svg.axis()
    .scale(x0)
    .orient("bottom");


var divTooltip = d3.select("#barrchart").append("div").attr("class", "toolTip");

var y   = d3.scale.linear()
              // Instead of using the whole array for the input domain, we use 0, since we 
              // want our y axis to start at 0, and the biggest value of our dataset
              // d3.max returns the largest value of an array
                //.domain([d3.max(function(d) { return d.valores; }), 0])
            // .domain([ d3.max(dataset, function(d) { return d3.max(d.valores, function(d) { return d.value; }); }),0])

             .range( [ height , 0] );

var yAxis = d3.svg.axis()
    .scale(y)
    .orient("left")

     .tickFormat(d3.format(".2s"));


x0.domain(dataset.map(function(d) { return d.label; }));
x1.domain(options).rangeRoundBands([0, x0.rangeBand()]);
y.domain([0, d3.max(dataset, function(d) { return d3.max(d.valores, function(d) { return d.value; }); })]);

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", ".91em")
    .style("text-anchor", "end")
    .text("Counts");

var bar = svg.selectAll(".bar")
    .data(dataset)
    .enter().append("g")
    .attr("class", "rect")
    .attr("transform", function(d) { return "translate(" + x0(d.label) + ",0)"; });

bar.selectAll("rect")
    .data(function(d) { return d.valores; })
    .enter().append("rect")
    .attr("width", x1.rangeBand())
    .attr("x", function(d) { return x1(d.name); })
    .attr("y", function(d) { return y(d.value); })
    .attr("value", function(d){return d.name;})
    .attr("height", function(d) { return height - y(d.value); })
    .style("fill", function(d) { return color(d.name); });

bar
    .on("mousemove", function(d){
        divTooltip.style("left", d3.event.pageX+10+"px");
        divTooltip.style("top", d3.event.pageY-25+"px");
        divTooltip.style("display", "inline-block");
        var x = d3.event.pageX, y = d3.event.pageY
        var elements = document.querySelectorAll(':hover');
        l = elements.length
        l = l-1
        elementData = elements[l].__data__
        //divTooltip.html((d.label)+"<br>"+elementData.name+"<br>"+elementData.value+"");
        divTooltip.html("Type:"+elementData.name+"</br>"+"Cout:"+elementData.value)
    });
bar
    .on("mouseout", function(d){
        divTooltip.style("display", "none");
    });

var legendOffset = width+20;
                    var legend = svg.selectAll('.legend')                     
                        .data(color.domain())                                   
                        .enter()                                                
                        .append('g')                                            
                        .attr('class', 'legend')                                
                        .attr('transform', function(d, i) 
                                    {                     
                                        var height = legendRectSize + legendSpacing;          
                                        var offset =  height * color.domain().length /2;     
                                        var horz = legendOffset;                       
                                        var vert = i * height+50;                       
                                            return 'translate(' + horz + ',' + vert + ')';        
                                    }
                                );                                                     
                        legend.append('rect')                                     
                        .attr('width', legendRectSize)                          
                        .attr('height', legendRectSize)                         
                        .style('fill', color)                                   
                        .style('stroke', color); 

                        legend.append('text')                                     
                        .attr('x', legendRectSize + legendSpacing)              
                        .attr('y', legendRectSize)              
                        .text(function(d) { return d });  



    }); 

</script>

可以否建议我如何解决该问题。

您已尝试使用此行为轴引入边距:

.style("padding", marginRatio.top + " " + marginRatio.right +  " " + marginRatio.bottom +  " " + marginRatio.left )

这似乎与Firefox搭配不好。 相反,您可以像注释掉一样,以常规方式添加其他g元素:

.append("g")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")");

运行代码:

 <!DOCTYPE html> <html> <head> <script data-require="d3@3.5.17" data-semver="3.5.17" src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.5.17/d3.js"></script> </head> <body> <div id="barrchart"></div> <script> //section 3 function getRatio(side) { return ((margin[side] / width) * 100) + "%"; } var margin = { left: 50, top: 10, right: 150, bottom: 30 }, width = 700, height = 210, // marginRatio converts margin absolute values to // percent values to keep SVG responsive marginRatio = { left: getRatio("left"), top: getRatio("top"), right: getRatio("right"), bottom: getRatio("bottom") }; var legendRectSize = 8; var legendSpacing = 8; var x0 = d3.scale.ordinal() .rangeRoundBands([0, width], .1); var x1 = d3.scale.ordinal(); /*var y = d3.scale.linear() .range([height, 0]);*/ var color = d3.scale.ordinal() .range(["#BF6666", "#AEA4A2", "#A5735C", "#BC957F", "#FF9F63", "#D0CC96", "#BCBC8F"]); /*var svg = d3.select("#barrchart").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 + ")");*/ var svg = d3.select("div#barrchart") // Create div to act as SVG container .append("div") .attr("id", "svg-container") // Add SVG that will contain Graph elements .append("svg") // Add margin to show axes //.style("padding", marginRatio.top + " " + marginRatio.right + " " + marginRatio.bottom + " " + marginRatio.left ) // Preserve aspect ratio xMinYmin ensures SVG fills #svg-container .attr("preserveAspectRatio", "xMinYMin meet") // Sets the viewbox, for more info on viewbox, combined with preveserveAspectRatio, this is what turns the bar chart // into a responsive bar chart .attr("viewBox", "0 0 " + (width + margin.left + margin.right) + " " + (height + margin.top + margin.bottom)) // Id to target with CSS .attr("id", "svg-content-responsive") .append("g") .attr("transform", "translate(" + margin.left + "," + margin.top + ")"); dataset = [{ label: "Pending", "a": 20, "b": 10, "c": 50 }, { label: "InProgress", "a": 15, "b": 30, "c": 40 }, { label: "Finished", "a": 20, "b": 25, "c": 20 }, { label: "Deliver", "a": 10, "b": 35, "c": 40 }]; var options = d3.keys(dataset[0]).filter(function(key) { return key !== "label"; }); dataset.forEach(function(d) { d.valores = options.map(function(name) { return { name: name, value: +d[name] }; }); }); var xAxis = d3.svg.axis() .scale(x0) .orient("bottom"); var divTooltip = d3.select("#barrchart").append("div").attr("class", "toolTip"); var y = d3.scale.linear() // Instead of using the whole array for the input domain, we use 0, since we // want our y axis to start at 0, and the biggest value of our dataset // d3.max returns the largest value of an array //.domain([d3.max(function(d) { return d.valores; }), 0]) // .domain([ d3.max(dataset, function(d) { return d3.max(d.valores, function(d) { return d.value; }); }),0]) .range([height, 0]); var yAxis = d3.svg.axis() .scale(y) .orient("left") .tickFormat(d3.format(".2s")); x0.domain(dataset.map(function(d) { return d.label; })); x1.domain(options).rangeRoundBands([0, x0.rangeBand()]); y.domain([0, d3.max(dataset, function(d) { return d3.max(d.valores, function(d) { return d.value; }); })]); 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", ".91em") .style("text-anchor", "end") .text("Counts"); var bar = svg.selectAll(".bar") .data(dataset) .enter().append("g") .attr("class", "rect") .attr("transform", function(d) { return "translate(" + x0(d.label) + ",0)"; }); bar.selectAll("rect") .data(function(d) { return d.valores; }) .enter().append("rect") .attr("width", x1.rangeBand()) .attr("x", function(d) { return x1(d.name); }) .attr("y", function(d) { return y(d.value); }) .attr("value", function(d) { return d.name; }) .attr("height", function(d) { return height - y(d.value); }) .style("fill", function(d) { return color(d.name); }); bar .on("mousemove", function(d) { divTooltip.style("left", d3.event.pageX + 10 + "px"); divTooltip.style("top", d3.event.pageY - 25 + "px"); divTooltip.style("display", "inline-block"); var x = d3.event.pageX, y = d3.event.pageY var elements = document.querySelectorAll(':hover'); l = elements.length l = l - 1 elementData = elements[l].__data__ //divTooltip.html((d.label)+"<br>"+elementData.name+"<br>"+elementData.value+""); divTooltip.html("Type:" + elementData.name + "</br>" + "Cout:" + elementData.value) }); bar .on("mouseout", function(d) { divTooltip.style("display", "none"); }); var legendOffset = width + 20; var legend = svg.selectAll('.legend') .data(color.domain()) .enter() .append('g') .attr('class', 'legend') .attr('transform', function(d, i) { var height = legendRectSize + legendSpacing; var offset = height * color.domain().length / 2; var horz = legendOffset; var vert = i * height + 50; return 'translate(' + horz + ',' + vert + ')'; }); legend.append('rect') .attr('width', legendRectSize) .attr('height', legendRectSize) .style('fill', color) .style('stroke', color); legend.append('text') .attr('x', legendRectSize + legendSpacing) .attr('y', legendRectSize) .text(function(d) { return d }); </script> </body> </html> 

暂无
暂无

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

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