python的plot函数x轴如何只显示一部分标签,matplotlib共享x轴,但不同时显示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.

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:

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()

34ef37249468393ef8a49d118ed0f7b4.png

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值