首页 > 解决方案 > 使用共享 x 轴更改一个子图的 xticks

问题描述

我想在许多子图中的一个子图中更改 xlimits 和 xticks,但它仅适用于 xticks。

我正在绘制许多图,几乎所有图都具有相同的 x 轴,在一个图中,因此决定使用plt.subplots(sharex=True). 对于一个情节,我希望我的 x 轴上有不同的限制和刻度。为此,我使用ax.get_shared_x_axes().remove(ax).


import matplotlib.pyplot as plt
fig, axes = plt.subplots(4,10,sharey=True, sharex=True)

axes_flat = axes.flat

for i in range(0,33) :
   xs = axes_flat[i]
   xs.plot([0,1,2],[2,3,4])
   xs.set_xticks([0,2])
   xs.set_xlim([0,4])


#leave some room between normal plots and plots with different xlims:
axes_flat[34].axis('off')
axes_flat[35].axis('off')

# Remove this plot from the shared axes and change xlims and xticks:
axes_flat[36].get_shared_x_axes().remove(axes_flat[36])
axes_flat[36].set_xticks([0,1])
axes_flat[36].set_xlim([0,2])

axes_flat[38].axis('off')
axes_flat[39].axis('off')

plt.show()

在此处输入图像描述

这适用于 x 限制,但不适用于 xticks。更改一个子图中的刻度会覆盖所有其他刻度,而 x 限制仅在子图中更改,这是我想要的。我不明白为什么set_xticks并且set_xlim在这种情况下会表现不同。有没有办法解决这个问题,同时还在使用 plt.subplots(sharex=True)

标签: pythonmatplotlibsubplot

解决方案


我不知道是否有办法使用 来做到这一点plt.subplots(shared=True),但我做了一些类似的事情,你可以这样做:

ax1 = plt.subplot(121)
ax1.set_ylim(0, means_sd['mean'].max()+2)
ax1.bar(x=0, bottom=0, width=0.8, height=ref, color='gray')
ax1.set_xticks(list(range(len(data))))
ax1.set_xticklabels(s for s in labels)


ax2 = plt.subplot(122)
ax2.set_ylim(0, means_sd['mean'].max()+2)
ax2.bar(x=0, bottom=0, width=0.8, height=ref, color='gray')
ax2.set_xticks(list(range(len(data))))
ax2.set_xticklabels(s for s in labels)

我希望这有帮助。


推荐阅读