Ale*_*aut 5 python plot numpy matplotlib
我想将 3D 数据投影到具有交互式共享轴的 XY、XZ、YZ 子图上。
import matplotlib.pyplot as plt
import numpy as np
fig, axes = plt.subplots(3, 1, constrained_layout=True)
n = 10000
pts = {
'X': np.random.normal(0, 1, n),
'Y': np.random.normal(0, 2, n),
'Z': np.random.normal(0, 4, n)
}
for ax, (k1, k2) in zip(axes, [('X', 'Y'), ('X', 'Z'), ('Y', 'Z')]):
ax.plot(pts[k1], pts[k2], ',')
ax.set_xlabel(k1)
ax.set_ylabel(k2)
axes[0].sharex(axes[1])
axes[1].sharey(axes[2])
plt.show()
Run Code Online (Sandbox Code Playgroud)

XY 和 XZ 图共享 X 轴限制,YZ 和 XZ 图共享 Z 轴限制,但如何使 XY 和 YZ 共享 Y 轴限制?也许某种语法axes[2].sharexy(axes[0])以某种方式存在?
我发现的一个快速(可能非常愚蠢)的修复方法是手动进行轴共享。换句话说,如果您想要共享的 x 轴和 y 轴在图中具有相同的尺寸(即它们的跨度例如 10 厘米),您可以手动将它们设置为具有相同的限制、刻度和刻度标签。在你的情况下,它会是这样的:
axes[0].set_ylim(axes[2].get_xlim()) #set the y lim of first subplot the same
#as x lim of last subplot
axes[0].set_yticks(axes[2].get_xticks()) #set y ticks of first subplot the same as
#x ticks of last subplot
#You can also do further stuff like turning off y ticks labels of axes[0]
#with something like plt.setp(axes[0].get_yticklabels(), visible=False).
Run Code Online (Sandbox Code Playgroud)
就我而言,在所有图形调整(subplots_adjust()等)之后执行此操作会产生与共享这两个轴非常相似的结果,并且还具有正确的刻度标签。手动调整“共享”后的 y 刻度标签axes[0]似乎更棘手,因为axes[2].get_xticklabels()返回一个 Text 对象数组,其中也有 x 和 y 位置。手动调整 y 刻度标签的另一个(脏)解决方法是axes[0]:
#list comprehension to get strings of each x ticks of last subplot
ax2xticklabels = [i.get_text() for i in axes[2].get_xticklabels()]
axes[0].set_yticklabels(ax2xticklabels) #set y tick labels of first subplot
#the same as x tick labels of last subplot
Run Code Online (Sandbox Code Playgroud)
实际上,我来这里也是为了寻找一种更优雅的方法来解决这个问题,但注意到互联网上似乎没有什么可以独立共享 2 个轴对象,我想分享我的肮脏的快速修复:D。希望这会有所帮助!