`sharex` 轴,但不显示两者的 x 轴刻度标签,仅显示一个
我正在使用 python + matplotlib 并且我有两个图共享一个轴。如果您尝试在共享轴时设置graph1.set_xticklabels([])
,则它不会产生任何效果,因为它是共享的。有没有一种方法可以共享轴并能够隐藏一个图的 x 轴?
I'm using python + matplotlib and I'm having two plots share an axis. If you try to set graph1.set_xticklabels([])
while sharing an axis, it has no effect because it is shared. Is there a way to share the axis AND be able to hide the x axis of one plot?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
这是使用共享轴时的常见问题。
幸运的是,有一个简单的修复方法:使用
plt.setp(ax. get_xticklabels(),visible=False)
使标签仅在一个轴上不可见。这相当于
[label.set_visible(False) for label in ax.get_xticklabels()]
,无论它的价值如何。setp
将自动对 matplotlib 对象的可迭代对象以及单个对象进行操作。例如:
This is a common gotcha when using shared axes.
Fortunately, there's a simple fix: use
plt.setp(ax.get_xticklabels(), visible=False)
to make the labels invisible on just one axis.This is equivalent to
[label.set_visible(False) for label in ax.get_xticklabels()]
, for whatever it's worth.setp
will automatically operate on an iterable of matplotlib objects, as well as individual objects.As an example:
根据 matplotlib-users 上的线程,您可以使用
Per a thread on matplotlib-users, you could use
您可以使用 Axes.tick_params():
当具有共享 x 轴的子图最初隐藏标签时,tick_params 方法也适用于相反的情况:
You could use Axes.tick_params():
The
tick_params
method works also in the opposite case, when the labels are initially hidden for subplots with shared x-axis:您可以在创建子图期间使用
plt.subplots
as
这将自动关闭内轴的刻度标签。
完整示例:
You can share the axes during subplot creation with
plt.subplots
asThis will automatically turn the ticklabels for inner axes off.
Complete example:
不幸的是,我不允许对 esmit 的答案发表评论(我认为这是最好的解决方案,谢谢 esmit),所以我必须将我的评论写为新答案:我将他的解决方案放入一个简单的函数中,
您可以在之前调用它
plt.show()
。由于某种原因,乔·金顿的回答对我不起作用。Unfortunately, I am not allowed to comment on esmit's answer (which is the best solution in my opinion, thanks esmit), so I have to write my comment as a new answer: I put his solution into a simple function
which you can call before
plt.show()
. Joe Kington's answer did not work for me for some reason.