1

I’m trying to fit a line chart into a div. I’m having a hard time fitting the entire chart, including x and y axes into the div. The x axis always ends up being hidden beyond the bottom extents of the div. I would like the chart, including the axes, to be visible and to automatically scale and fit into the container div, even if the dimensions of the div change. In other words, I’d like it to behave just like a chart in Microsoft Excel.

This is the JavaScript. I think I’m fundamentally misunderstanding the viewBox attribute

//get width and height of container div    
var div_w = d3.select("#container").style("width").split("px").shift();
var div_h = d3.select("#container").style("height").split("px").shift();

// Add an SVG element with the desired dimensions and margin.
var graph = d3.select("#container”)
    .append("svg:svg")
    .attr("viewBox","0 0 " + div_w +" " + div_h)
    .attr("preserveAspectRatio", "xMinYMin meet")
    .append("svg:g")
    .attr("transform", "translate(" + m[3] + "," + m[0] + ")");

//Here is the resulting html
<div  class=”container”>
    <svg>
        <g>
            <g class=”x axis”>
                <g class=”tick”
                    <line  attributes…..
                    <text attributes…..
                </g>
        </g>
    </svg>
</div>

I was looking in the wrong place for this solution. Later on in the code, when the x-axis was appended to the div container, I moved the axis down h units (h is the height of the div container) by using the transform attribute, hence the axis would end up below the bottom extents of the container. Needed only to move it down h-m[1] units (height - bottom margin). This at least takes care of the x-axis visibility issue. Haven't tackled the re-sizing with the div issue.

    //WRONG WAY    
    // Add the x-axis.
        graph.append("svg:g")
              .attr("class", "x axis")
              .attr("transform", "translate(0," + h + ")")
              .call(xAxis);

    //RIGHT WAY
    // Add the x-axis.
        graph.append("svg:g")
              .attr("class", "x axis")
              .attr("transform", "translate(0," + (h-m[1]) + ")")
              .call(xAxis);
Community
  • 1
  • 1
Chris
  • 33
  • 2
  • 6

1 Answers1

1

Your second parenthesis in the first two lines after #container are weird.

Try pasting this instead and see if it works:

var div_w = d3.select("#container").style("width").split("px").shift();
var div_h = d3.select("#container").style("height").split("px").shift();
A.L
  • 10,259
  • 10
  • 67
  • 98
Ana
  • 11
  • 1