Python Matplotlib图中图实现方案问询:Tkinter GUI预构建Figure嵌入新Figure
Great question! Embedding one full Figure object into another isn’t a standard or supported workflow in Matplotlib—figures are top-level containers designed to be standalone. Instead, the cleanest approach is to recreate your subplot grid directly within your existing Tkinter-attached Figure (f) rather than creating a separate new figure. Here’s how to do it:
Step 1: Clear Existing Content (Optional but Recommended)
If your original f has any existing subplots, start by removing them to avoid overlapping content:
# Remove all existing axes from the figure for ax in f.axes: ax.remove()
Step 2: Create the Subplot Grid in Your Existing Figure
Instead of using plt.subplots() (which generates a new figure), use the subplots() method directly on your existing f object. This replicates your 2x3 grid with shared axes:
# Create the 2x3 subplot grid in your existing Figure f axes = f.subplots(nrows=2, ncols=3, sharex=True, sharey=True)
Step 3: Plot Your Contour Plots
You can reuse your existing plotting code exactly as before—axes will be the array of subplot axes within f:
for i, ax in enumerate(axes.flat): contourplot = ax.contourf(A, B, mag[i])
Step 4: Update the Tkinter View
Finally, call f.draw() to render the new content in your Tkinter GUI:
f.draw()
Why This Works Better Than Embedding Figures
Matplotlib’s design centers around a single Figure containing multiple Axes (subplots). Trying to nest one figure inside another would require hacky workarounds (like converting the figure to a static image and plotting that), which breaks interactivity and complicates updates. By building the subplot grid directly in your existing Tkinter figure, you maintain full control over interactivity, styling, and future updates.
If you absolutely need to reuse an already-created figure’s content (e.g., you can’t easily re-run the plotting code), you could copy individual plot elements from the new figure’s axes to corresponding axes in f, but this is far more error-prone and not recommended for most cases.
内容的提问来源于stack exchange,提问作者Sam

