Bohn
Bohn

Reputation: 26919

Placing two elements - charts - under each other on the page

I have a piece of D3.js code that draws a chart, and it width,height,etc.. are set like this:

<script>

    var margin = {top: 20, right: 20, bottom: 30, left: 40},
            width = 960 - margin.left - margin.right,
            height = 500 - margin.top - margin.bottom;

And it draws fine on the page. To be exact: The script tag from this source: https://github.com/mhemesath/r2d3/blob/master/examples/scatterplot/scatterplot.html

Then I copy-paste another piece of D3.js code that draws a bar chart and its width, height, etc... are set like this:

<script type="text/javascript">

    //Width and height
    var w = 500;
    var h = 100;
    var barPadding = 1;

To be exact: The script tag from this source code: http://alignedleft.com/content/3.tutorials/10.d3/130.making-a-bar-chart/demo/10.html

How can I tell them not to overlap each other, I just simply want them for first one to show, then at the bottom of it the next one to show...

Upvotes: 1

Views: 1739

Answers (2)

Adithya
Adithya

Reputation: 339

There are two options for your questions :

  1. DIFFERENT SVG ELEMENTS : As pointed out by my friend above you can put in two different svg tags with different class name.

    var svg1 = d3.select(body)
                  .append(svg)
                  .attr('class', 'chart1')
    
    var svg2 = d3.select(body)
              .append(svg)
              .attr('class', 'chart2')
    

Then you can just use the variable

          svg1.append('rect').data().enter()
          svg2.append('rect').data().enter()
  1. Using Grouping (G) Tag: This allows you to group various charts in the svg but different G tags . You can think of them as Div tags for the Html.

You can see following post for d3: redraw function with g containers

Upvotes: 1

Andrew Staroscik
Andrew Staroscik

Reputation: 2704

One way is to create two separate svg elements and append them both to the body. See this gist for a demonstration. Notice each svg var has its own name (svgOne and svgTwo).

Upvotes: 2

Related Questions