You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何让Plotly.js图表仅自适应父div宽度且不导致父div溢出

Fix Plotly.js Pie Chart to Fit Parent Div Width (No Overflow)

Hey there, let's get your pie chart fitting perfectly to its parent div's width without causing any overflow issues. Here's how to adjust your code and setup properly:

Step 1: Give Your Parent Div Clear Width Rules

First, make sure the <div id="myChart1"> has an explicit width set so Plotly knows exactly what container it's adapting to. Throw this in your CSS:

#myChart1 {
  width: 90%; /* Adjust this to match your layout needs */
  max-width: 1000px; /* Optional: Stop it from getting too wide on big screens */
  margin: 0 auto; /* Optional: Centers the chart horizontally */
}

Step 2: Update Your Plotly Code

The default autosize: true can sometimes mess with height and cause overflow. Instead, we'll lock the chart to its parent's width, control the height, and turn on responsiveness. Here's the revised code:

// Your data stays exactly the same
var data = [{ 
  type: "pie", 
  values: [2, 3, 4, 4], 
  labels: ["Wages", "Operating expenses", "Cost of sales", "Insurance"], 
  textinfo: "label+percent", 
  textposition: "outside", 
  automargin: true 
}];

// Updated layout to target parent width and prevent overflow
var layout = {
  width: '100%', // Chart takes full width of its parent div
  height: 500, // Fixed height (adjust as needed; use '80vh' for responsive height)
  showlegend: true, 
  title: "Expense Status",
  margin: { t: 60, b: 20, l: 20, r: 20 } // Adds buffer so content doesn't touch div edges
};

// Config to make the chart respond when parent div resizes
var config = {
  responsive: true, // Updates chart automatically if parent width changes
  maintainAspectRatio: false // Lets us control width and height independently
};

// Render the chart with all our settings
Plotly.newPlot('myChart1', data, layout, config);

Quick Notes on What Each Setting Does

  • width: '100%': Forces the chart to match the parent div's width exactly—no overflow, no gaps.
  • Fixed/Responsive Height: Setting a fixed height (like 500px) stops the chart from stretching vertically and pushing the parent div out of bounds. If you want height to adapt too, use a relative unit like '80vh' (80% of the viewport height).
  • responsive: true: Makes sure the chart resizes automatically if the parent div's width changes (e.g., when someone resizes their browser window).
  • automargin: true on the trace: Ensures pie labels don't get cut off when the chart shrinks to a smaller width.

This setup will keep your chart neatly contained in its parent div, adapting only to the parent's width without any overflow issues.

内容的提问来源于stack exchange,提问作者Raman

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.28 16:47:42