在 Python/Matplotlib 中,如何在同一张图上绘制两个不共享任何轴的图?即,第一个图使用左轴和下轴,第二个图使用上轴和右轴。每对轴都是独立的,将用于在同一个图形上独立绘制多条曲线。 例如,这通常用于主成分分析的双标图。
据我所知,我的解决方案不是通过 twinx 或 twiny,而且我还没有找到使用 host_suplot< 的解决方案 两者都不是……而且我所有的研究都引导我找到具有共享轴的解决方案,这些解决方案无法解决这种特殊情况。 谢谢。
请您参考如下方法:
不是很优雅,但它有效。
import numpy as np
import matplotlib.pyplot as plt
x1 = np.arange(10)
y1 = x1**2
x2 = np.arange(100,200)
y2 = x2
fig = plt.figure()
ax1 = fig.add_axes([0.1, 0.1, 0.8, 0.8], label="ax1")
ax2 = fig.add_axes([0.1, 0.1, 0.8, 0.8], label="ax2", frameon=False)
ax1.yaxis.tick_left()
ax1.xaxis.tick_bottom()
ax2.yaxis.tick_right()
ax2.yaxis.set_label_position('right')
ax2.yaxis.set_offset_position('right')
ax2.xaxis.tick_top()
ax2.xaxis.set_label_position('top')
ax1.spines['right'].set_color('red')
ax1.spines['top'].set_color('red')
for ylabel, xlabel in zip(ax2.get_yticklabels(), ax2.get_xticklabels()):
ylabel.set_color("red")
xlabel.set_color("red")
ax1.plot(x1,y1)
ax2.plot(x2,y2, 'r')
plt.show()
