Setting the Title, Legend Entries, and Axis Titles in JavaScript

How to set the title, legend-entries, and axis-titles in javascript D3.js-based charts.


New to Plotly?

Plotly is a free and open-source graphing library for JavaScript. We recommend you read our Getting Started guide for the latest installation or upgrade instructions, then move on to our Plotly Fundamentals tutorials or dive straight in to some Basic Charts tutorials.

var trace1 = {
  x: [0, 1, 2, 3, 4, 5, 6, 7, 8],
  y: [0, 1, 2, 3, 4, 5, 6, 7, 8],
  name: 'Name of Trace 1',
  type: 'scatter'
};
var trace2 = {
  x: [0, 1, 2, 3, 4, 5, 6, 7, 8],
  y: [1, 0, 3, 2, 5, 4, 7, 6, 8],
  name: 'Name of Trace 2',
  type: 'scatter'
};
var data = [trace1, trace2];
var layout = {
  title: {
    text:'Plot Title',
    font: {
      family: 'Courier New, monospace',
      size: 24
    },
    xref: 'paper',
    x: 0.05,
  },
  xaxis: {
    title: {
      text: 'x Axis',
      font: {
        family: 'Courier New, monospace',
        size: 18,
        color: '#7f7f7f'
      }
    },
  },
  yaxis: {
    title: {
      text: 'y Axis',
      font: {
        family: 'Courier New, monospace',
        size: 18,
        color: '#7f7f7f'
      }
    }
  }
};

Plotly.newPlot('myDiv', data, layout);

Set automargin to true to allow the title to push the figure margins. With yref set to paper, automargin expands the margins to make the title visible, but doesn't push outside the container. With yref set to container, automargin expands the margins, but doesn't overlap with the plot area, tick labels, and axis titles.

var trace1 = {
  x: [1952, 1957, 1962, 1967, 1972, 1977, 1982, 1987, 1992, 1997, 2002, 2007],
  y: [69.39,
      70.26,
      71.24,
      71.52,
      71.89,
      72.22,
      73.84,
      74.32,
      76.33,
      77.55,
      79.11,
      80.204
  ],
  type: 'scatter'
};
var trace2 = {
  x: [1952, 1957, 1962, 1967, 1972, 1977, 1982, 1987, 1992, 1997, 2002, 2007],
  y: [69.12,
      70.33,
      70.93,
      71.1,
      71.93,
      73.49,
      74.74,
      76.32,
      77.56,
      78.83,
      80.37,
      81.235
  ],
  type: 'scatter'
};
var data = [trace1, trace2];
var layout = {
  title: {
      text: 'Population',
      font: {
          family: 'Courier New, monospace',
          size: 70
      },
      yref: 'paper',
      automargin: true,
  },
  showlegend: false
};

Plotly.newPlot('myDiv', data, layout);