如何从自定义函数中返回可后续绘制或用于网页的子图(subplot)图形?
Hey there! Let's work through this together—returning your matplotlib/seaborn figures for later use is totally straightforward once you know which objects to pass back. First, let's fix up your example code (it has a couple small syntax issues we'll sort out), then walk through exactly how to return the figure for reuse.
Step 1: Clean Up Your Base Code
First, a quick note on your current code:
plt.subplots(1, 2)creates a 1-row, 2-column grid, soaxis a 1-dimensional array (not 2D). You don't needax[0][0]—it should beax[0]for the first subplot,ax[1]for the second.- You missed a closing parenthesis on
sns.barplot(), and newer seaborn versions require explicit keyword arguments (x=x, y=y) instead of positional ones. - Pie plots in matplotlib expect values first, then labels (I adjusted that in the example below to avoid errors).
Here's the cleaned-up base code:
import matplotlib.pyplot as plt import seaborn as sns def plot_g(x, y): # Create figure and 1x2 subplot grid fig, ax = plt.subplots(1, 2, figsize=(18, 14)) # Bar plot on first subplot sns.barplot(x=x, y=y, ax=ax[0]) # Pie plot on second subplot ax[1].pie(y, labels=x) # Return the figure object here! return fig
Step 2: Return the Right Object
The fig variable (from plt.subplots()) is the entire container for your graphic—it holds all your subplots, styling, and layout. Returning this gives you full control over the plot later:
- Save it to a file (PNG, SVG, etc.)
- Display it in a notebook or desktop app
- Modify elements like titles, labels, or colors after calling the function
- Convert it to a format usable in web apps
Step 3: Use the Returned Figure
Once you return fig, you can use it like this:
# Call your function and store the returned figure my_plot = plot_g(x=["A", "B", "C"], y=[15, 30, 22]) # Example 1: Save the figure to a file (with tight cropping to avoid cut-off labels) my_plot.savefig("my_combined_plot.png", dpi=300, bbox_inches="tight") # Example 2: Show the figure (works in Jupyter notebooks or desktop Python environments) plt.show() # Example 3: Modify subplots after the fact all_subplots = my_plot.axes # Get list of all subplots from the figure all_subplots[0].set_title("My Bar Chart") # Add title to first subplot all_subplots[1].set_title("My Pie Chart") # Add title to second subplot my_plot.savefig("updated_plot.png")
Bonus: Return Axes for Direct Subplot Control
If you want to work directly with individual subplots instead of the whole figure, you can return ax (the array of subplots) too—or both objects:
def plot_g(x, y): fig, ax = plt.subplots(1, 2, figsize=(18, 14)) sns.barplot(x=x, y=y, ax=ax[0]) ax[1].pie(y, labels=x) return fig, ax # Return both the figure and subplot axes # Usage fig, ax = plot_g(x=["A", "B", "C"], y=[15, 30, 22]) ax[0].set_xlabel("Categories") # Modify first subplot directly fig.savefig("final_plot.png")
That's all there is to it! Returning fig (and/or ax) lets you reuse and tweak your plot however you need, whether that's for additional edits, saving, or embedding in a web interface.
内容的提问来源于stack exchange,提问作者Darkstar Dream

