Keywords: Matplotlib | Multi-figure Display | Figure Management | Data Visualization | Python Programming
Abstract: This article provides an in-depth exploration of common issues and solutions for displaying multiple figures simultaneously in Matplotlib. By analyzing real user code problems, it explains the timing of plt.show() calls, multi-figure management mechanisms, and differences between explicit and implicit interfaces. Combining best answers with official documentation, the article offers complete code examples and practical advice to help readers master core techniques for multi-figure display in Matplotlib.
Problem Background and Phenomenon Analysis
When using Matplotlib for data visualization, many developers encounter issues with displaying multiple figures simultaneously. From the provided code example, we can see that the user attempted to create two independent histograms, but only the first figure displayed properly. The root cause of this phenomenon lies in insufficient understanding of Matplotlib's figure management mechanism.
Matplotlib Figure Management Mechanism
Matplotlib employs the concept of a current figure to manage multiple figures. When plt.figure(n) is called, the system sets the figure with number n as the current figure. If such a figure doesn't exist, a new one is automatically created. While this mechanism is convenient, it can easily cause confusion, especially when handling multiple figures.
According to official documentation recommendations, we discourage handling multiple figures through the implicit pyplot interface because managing the current figure is both cumbersome and error-prone. Instead, we recommend using explicit methods and calling methods directly on Figure and Axes instances.
Detailed Solution Explanation
For the multi-figure display problem, the optimal solution involves controlling the display timing of each figure separately. The specific implementation is as follows:
# Create and configure first figure
f = plt.figure(1)
plt.hist(tlist_first, bins=2000000, normed=True, histtype="step", cumulative=True, color="g", label="first answer")
plt.ylabel("Percentage of answered questions")
plt.xlabel("Minutes elapsed after questions are posted")
plt.axvline(x=30, ymin=0, ymax=1, color="r", linestyle="--", label="30 min")
plt.axvline(x=60, ymin=0, ymax=1, color="c", linestyle="--", label="1 hour")
plt.legend()
plt.xlim(0,120)
plt.ylim(0,1)
f.show()
# Create and configure second figure
g = plt.figure(2)
plt.hist(tlist_first, bins=2000000, normed=True, histtype="step", cumulative=True, color="g", label="first answer")
plt.ylabel("Percentage of answered questions")
plt.xlabel("Minutes elapsed after questions are posted")
plt.axvline(x=240, ymin=0, ymax=1, color="r", linestyle="--", label="30 min")
plt.axvline(x=1440, ymin=0, ymax=1, color="c", linestyle="--", label="1 hour")
plt.legend(loc=4)
plt.xlim(0,2640)
plt.ylim(0,1)
g.show()
# Keep figures displayed
input()
Key Points Analysis
The core advantages of this solution are:
First, by assigning figure objects to variables (such as f and g), we can precisely control the display timing of each figure. Calling f.show() and g.show() displays the two figures separately, avoiding the limitation of plt.show() displaying all current figures at once.
Second, using the input() function (or raw_input() in Python 2) maintains the active state of figure windows. This step is crucial because without this blocking call, figure windows might close immediately after script execution completes.
Finally, this method allows dynamic selection of which figures to display, providing greater flexibility for interactive data analysis and debugging.
Alternative Solutions Comparison
Besides the optimal solution described above, other viable approaches exist:
A common method involves calling plt.show() only once after creating all figures. While this approach is simple, it lacks fine-grained control over individual figures. In some cases, if the figure creation process is complex or requires user interaction, this method may not be flexible enough.
Another approach uses Matplotlib's object-oriented interface, directly manipulating Figure and Axes objects. Although this method has a steeper learning curve, it provides the most powerful control capabilities, particularly suitable for complex visualization requirements.
Practical Recommendations and Considerations
In practical applications, we recommend that developers:
For simple multi-figure display needs, adopt the optimal solution introduced in this article, which ensures both functional completeness and code simplicity.
For complex visualization projects, gradually transition to object-oriented programming style, directly using explicit interfaces like fig, ax = plt.subplots(), which provides better control over various components of figures.
It's important to note that different backends (such as TkAgg, Qt5Agg, etc.) may have subtle differences in handling multi-figure display. For cross-platform development, thorough testing is recommended.
Additionally, when handling large numbers of figures, promptly release figure resources that are no longer needed to avoid memory leak issues. Specific figures can be closed by calling plt.close().
Conclusion
While Matplotlib's multi-figure display functionality is powerful, correctly understanding its internal mechanisms is essential to fully leverage its capabilities. By mastering the fundamental principles and best practices of figure management, developers can easily create complex multi-figure visualizations to meet various data analysis requirements.