Matplotlib能否创建带有寄生轴的子图?
Answer
Absolutely, Matplotlib does support creating subplots with parasite axes—you just need to make sure each subplot has its own independent host/parasite axis setup. The blank subplots you're seeing are likely because you're reusing the same axis grid structure across both subplots, or not properly initializing the parasite axes for each individual subplot.
Let's walk through a corrected example that creates two subplots, each with their own parasite axis:
from mpl_toolkits.axes_grid1 import host_subplot import mpl_toolkits.axisartist as AA import matplotlib.pyplot as plt # Create a figure with 2 side-by-side subplots fig = plt.figure(figsize=(12, 5)) # --- Set up first subplot with parasite axis --- host1 = host_subplot(121, axes_class=AA.Axes, figure=fig) plt.subplots_adjust(right=0.75) # Add parasite axis to the first subplot parasite1 = host1.twinx() parasite1.axis["right"].toggle(all=True) # Plot sample data on host and parasite axes host1.plot([1, 2, 3], [10, 20, 30], label="Host Dataset 1") parasite1.plot([1, 2, 3], [0.1, 0.2, 0.3], label="Parasite Dataset 1", color="crimson") # Configure labels and legend for first subplot host1.set_xlabel("X Values") host1.set_ylabel("Host Y Axis") parasite1.set_ylabel("Parasite Y Axis") host1.legend() # --- Set up second subplot with parasite axis --- host2 = host_subplot(122, axes_class=AA.Axes, figure=fig) # Add parasite axis to the second subplot parasite2 = host2.twinx() parasite2.axis["right"].toggle(all=True) # Plot different sample data on the second subplot host2.plot([1, 2, 3], [5, 15, 25], label="Host Dataset 2") parasite2.plot([1, 2, 3], [0.05, 0.15, 0.25], label="Parasite Dataset 2", color="darkgreen") # Configure labels and legend for second subplot host2.set_xlabel("X Values") host2.set_ylabel("Host Y Axis 2") parasite2.set_ylabel("Parasite Y Axis 2") host2.legend() # Adjust layout to prevent label overlap plt.tight_layout() plt.show()
Key Fixes & Notes:
- Each subplot gets its own
host_subplotinstance, explicitly tied to the figure and its position (using121and122for 1 row, 2 columns, positions 1 and 2). - We explicitly toggle the parasite axis visibility with
parasite.axis["right"].toggle(all=True)to ensure it renders properly. - Avoid reusing a single
AxesGridor host axis across multiple subplots—each needs its own independent setup. - Using
plt.subplots_adjustorplt.tight_layout()helps prevent overlapping axis labels and improves readability.
内容的提问来源于stack exchange,提问作者Alex S
相关产品推荐
相关产品推荐

