matplotlib共享x轴,但不同时显示x轴刻度标签,只有一个 [英] matplotlib share x axis but don't show x axis tick labels for both, just one

查看:814
本文介绍了matplotlib共享x轴,但不同时显示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?

推荐答案

这是使用共享轴时的常见陷阱.

This is a common gotcha when using shared axes.

幸运的是,有一个简单的解决方法:使用 plt.setp(ax.get_xticklabels(), visible=False) 使标签仅在一个轴上不可见.

Fortunately, there's a simple fix: use plt.setp(ax.get_xticklabels(), visible=False) to make the labels invisible on just one axis.

这等同于[label.set_visible(False) for label in ax.get_xticklabels()],无论其价值如何. setp将自动对可迭代的matplotlib对象以及单个对象进行操作.

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.

例如:

import matplotlib.pyplot as plt
fig = plt.figure()
ax1 = fig.add_subplot(2,1,1)
ax1.plot(range(10), 'b-')

ax2 = fig.add_subplot(2,1,2, sharex=ax1)
ax2.plot(range(10), 'r-')

plt.setp(ax1.get_xticklabels(), visible=False)

plt.show()

这篇关于matplotlib共享x轴,但不同时显示x轴刻度标签,只有一个的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆