[英]matplotlib share x axis but don't show x axis tick labels for both, just one
我正在使用python + matplotlib,并且我有两个图共享一个轴。 如果尝试在共享轴时设置graph1.set_xticklabels([])
,则由于共享,因此它无效。 有没有一种共享轴并能够隐藏一个绘图的x轴的方法?
使用共享轴时,这是常见的陷阱。
幸运的是,有一个简单的解决方法:使用plt.setp(ax.get_xticklabels(), visible=False)
使标签仅在一个轴上不可见。
无论价值多少,它等效于[label.set_visible(False) for label in ax.get_xticklabels()]
。 setp
将自动对可迭代的matplotlib对象以及单个对象进行操作。
举个例子:
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-users上的一个线程,您可以使用
import matplotlib.pyplot as plt
for ax in plt.gcf().axes:
try:
ax.label_outer()
except:
pass
您可以使用Axes.tick_params() :
import matplotlib.pyplot as plt
fig = plt.figure()
ax1 = fig.add_subplot(211)
ax2 = fig.add_subplot(212, sharex=ax1)
ax1.tick_params(labelbottom=False)
您可以在创建子图期间使用plt.subplots
共享轴, plt.subplots
:
fig, axes = plt.subplots(nrows=2, sharex=True)
这将自动关闭内轴的刻度标签。
完整的例子:
import matplotlib.pyplot as plt
fig, axes = plt.subplots(nrows=2, sharex=True)
axes[0].plot([1,2,3])
axes[1].plot([3,2,1])
plt.show()
不幸的是,我不允许对esmit的答案发表评论(这是我认为这是最好的解决方案,谢谢esmit),因此我必须将评论写为新答案:我将其解决方案放入了一个简单的函数中
def remove_inner_ticklabels(fig):
for ax in fig.axes:
try:
ax.label_outer()
except:
pass
您可以在plt.show()
之前调用它。 Joe Kington的回答由于某种原因对我不起作用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.