Setting Graph Size in JavaScript

How to change the size of D3.js-based graphs in javascript.


Plotly Studio: Transform any dataset into an interactive data application in minutes with AI. Try Plotly Studio now.

var data = [
  {
    x: [0, 1, 2, 3, 4, 5, 6, 7, 8],
    y: [0, 1, 2, 3, 4, 5, 6, 7, 8],
    type: 'scatter'
  }
];
var layout = {
  autosize: false,
  width: 500,
  height: 500,
  margin: {
    l: 50,
    r: 50,
    b: 100,
    t: 100,
    pad: 4
  },
  paper_bgcolor: '#7f7f7f',
  plot_bgcolor: '#c7c7c7'
};
Plotly.newPlot('myDiv', data, layout);
</script>\n</head>\n\n<body>\n\t<div id='myDiv'><!-- Plotly chart will be drawn inside this DIV --></div>\n</body>","js":"var data = [\n {\n x: [0, 1, 2, 3, 4, 5, 6, 7, 8],\n y: [0, 1, 2, 3, 4, 5, 6, 7, 8],\n type: 'scatter'\n }\n];\nvar layout = {\n autosize: false,\n width: 500,\n height: 500,\n margin: {\n l: 50,\n r: 50,\n b: 100,\n t: 100,\n pad: 4\n },\n paper_bgcolor: '#7f7f7f',\n plot_bgcolor: '#c7c7c7'\n};\nPlotly.newPlot('myDiv', data, layout);\n"}">

Set automargin=true (reference) and Plotly will automatically increase the margin size to prevent ticklabels from being cut off or overlapping with axis titles.

var data = [
  {
    x: ['Apples', 'Oranges', 'Watermelon', 'Pears'],
    y: [3, 2, 1, 4],
    type: 'bar'
  }
];
var layout = {
  autosize: false,
  width: 500,
  height: 500,
  yaxis: {
    title: {
      text: 'Y-axis Title',
      font: { size: 30 }
    },
    ticktext: ['long label','Very long label','3','label'],
    tickvals: [1, 2, 3, 4],
    tickmode: 'array',
    automargin: true,
  },
  paper_bgcolor: '#7f7f7f',
  plot_bgcolor: '#c7c7c7'
};
Plotly.newPlot('myDiv', data, layout);
</script>\n</head>\n\n<body>\n\t<div id='myDiv'><!-- Plotly chart will be drawn inside this DIV --></div>\n</body>","js":"var data = [\n {\n x: ['Apples', 'Oranges', 'Watermelon', 'Pears'],\n y: [3, 2, 1, 4],\n type: 'bar'\n }\n];\nvar layout = {\n autosize: false,\n width: 500,\n height: 500,\n yaxis: {\n title: {\n text: 'Y-axis Title',\n font: { size: 30 }\n },\n ticktext: ['long label','Very long label','3','label'],\n tickvals: [1, 2, 3, 4],\n tickmode: 'array',\n automargin: true,\n },\n paper_bgcolor: '#7f7f7f',\n plot_bgcolor: '#c7c7c7'\n};\nPlotly.newPlot('myDiv', data, layout);\n"}">