Search code examples
javascripthtmlplotly

How to show two Plotly charts side-by-side in JavaScript


I want to have two Plotly charts appear next to one another on the same line. Presently one chart appears above the other.

current

This is my JavaScript code for the two graphs:

    var barData = [
    {
        x: x_names,
        y: y_data,
        text: y_names,
        marker: { color: 'rgba(202,210,211,.90)' },
        type: 'bar',
        orientation: 'v',
        width: 0.8,
        options: { offset: true }
    }];

var barLayout = {
    title: "<b>Arrears Balance Managed by CSM</b>",
    showlegend: false,
    xaxis: { tickangle: 45, zeroline: true },
    yaxis: { gridwidth: 1, zeroline: true },
    height: 400,
    width: 500,

};

Plotly.newPlot('bar', barData, barLayout);

var donutData = [{
    labels: y1_names,
    values: x1_data,
    hole: .4,
    type: "pie"
}];

var donutLayout = {
    height: 400,
    width: 500,
    margin: {"t": 0, "b": 0, "l": 0, "r": 0},
    showlegend: true
    }

Plotly.newPlot('pie', donutData, donutLayout);

The following is from my html document:

  <h3 class='display-4'>Graphs</h3>

  <div class="col-md-6">
    <div id="bar">
  </div>

  <div class="col-md-6">
    <div id="pie">
  </div>

Is there a way to get the two charts to line up next to one another?

Thanks in advance for your help.


Solution

  • If you are using a modern browser with your web page. I suggest you use the following CSS: display: flex;. Here is a link to a good guide: https://css-tricks.com/snippets/css/a-guide-to-flexbox/

    You can also see the example I made in the code snippet:

    .graph-container {
      display: flex;
    }
    
    #bar {
      flex: 1;
      width: 50px;
      height: 50px;
      background-color: #FF0000;
    }
    
    #pie {
      flex: 1;
      width: 50px;
      height: 50px;
      background-color: #0000FF;
    }
    <h3 class='display-4'>Graphs</h3>
    <div class='graph-container'>
      <div id="bar"></div>
      <div id="pie"></div>
    </div>