python - 使用共享 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)
?
解决方案
我不知道是否有办法使用 来做到这一点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)
我希望这有帮助。
推荐阅读
- c++ - hello-world.cc 示例似乎泄漏了内存
- c# - .Net Core如何调试路由404问题
- macos - CS32F103C8T6 blue-pill 克隆 - 无法从 AC6 SystemWorkbench 中闪烁
- python - Paramiko ssh 进入 ec2 实例:抛出 Private Key File is Encrypted,但只有一半时间
- r - 如何以复杂的方式编写依赖于我的数据的 R 代码?
- r - 如何根据 r 中的两列分类值提取前 2 个最高总和值?
- serialization - Java对象序列化中嵌套对象原始值的java.lang.StackOverflowError异常
- firebase - 为什么在通过 Firebase 身份验证传递 id 令牌时,此 CORS 身份验证的 Google Cloud 函数会返回 403?
- bash - 在 Bash 中计算 txt 文件中不同单词的数量
- azure-active-directory - 从使用 MSAL 调用 acquireTokenSilent 返回的 accessToken 是否总是应该是 JWT?如果不是呢?