首页 文章

Matplotlib:使用twinx()和cla()清除第二个轴后无法重新绘制第一个轴

提问于
浏览
1

第二轴我有一个奇怪的问题......不确定我做错了什么 .

来自twinx example双轴代码

import numpy as np
import matplotlib.pyplot as plt

fig, ax1 = plt.subplots()


t = np.arange(0.01, 10.0, 0.01)
s1 = np.exp(t)
ax1.plot(t, s1, 'b-')
ax1.set_xlabel('time (s)')
# Make the y-axis label and tick labels match the line color.
ax1.set_ylabel('exp', color='b')
for tl in ax1.get_yticklabels():
    tl.set_color('b')

ax2 = ax1.twinx()
s2 = np.sin(2*np.pi*t)
ax2.plot(t, s2, 'r.')
ax2.set_ylabel('sin', color='r')
for tl in ax2.get_yticklabels():
    tl.set_color('r')

plt.show()

我得到下图 .

sample

如果我在绘制之前通过在 plt.show() 之前添加 ax1.cla() 来清除第一个轴,它将按预期清除第一个轴 .

clear first axis

如果我在绘图之前通过在 plt.show() 之前添加 ax2.cla() 来清除第二个轴,它会清除两个轴 . 不尽如人意,但似乎是a known issue . (编辑:也许它没有完全清除两个轴,轴标签仍然是第一轴的蓝色......)

enter image description here

就我的目的而言,这不是问题,因为我想要清除两个轴 . 但是当我试图重新绘制情节时,我遇到的问题就出现了 . 如果我运行以下设置两个轴的代码,则清除两个轴,然后再次设置它们 .

import numpy as np
import matplotlib.pyplot as plt

fig, ax1 = plt.subplots()


t = np.arange(0.01, 10.0, 0.01)
s1 = np.exp(t)
ax1.plot(t, s1, 'b-')
ax1.set_xlabel('time (s)')
# Make the y-axis label and tick labels match the line color.
ax1.set_ylabel('exp', color='b')
for tl in ax1.get_yticklabels():
    tl.set_color('b')

ax2 = ax1.twinx()
s2 = np.sin(2*np.pi*t)
ax2.plot(t, s2, 'r.')
ax2.set_ylabel('sin', color='r')
for tl in ax2.get_yticklabels():
    tl.set_color('r')

# single line addition to the two_scales.py example
# clears both ax2 and ax1 under matplotlib 1.4.0, clears only ax2 under matplotlib 1.3.1
# obviously, same result with ax2.clear() method
ax1.cla()    
ax2.cla()

# Set up the axis again

t = np.arange(0.01, 10.0, 0.01)
s1 = np.exp(t)
ax1.plot(t, s1, 'b-')
ax1.set_xlabel('time (s)')
# Make the y-axis label and tick labels match the line color.
ax1.set_ylabel('exp', color='b')
for tl in ax1.get_yticklabels():
    tl.set_color('b')

ax2 = ax1.twinx()
s2 = np.sin(2*np.pi*t)
ax2.plot(t, s2, 'r.')
ax2.set_ylabel('sin', color='r')
for tl in ax2.get_yticklabels():
    tl.set_color('r')


plt.show()

我看到了下图 . 由于某种原因,当我重新绘制两个轴时,它不会显示第一个轴 .

enter image description here

我做错了还是预期会出现这种情况?是否有任何变通方法可以清除和重新绘制两个轴图?

1 回答

  • 2

    我认为问题是你通过再次调用 twinx 来创建一个新的 ax2 . 但原来的孪生轴仍然存在,并且由于你提到的错误,它设置为不透明,因此它仍然隐藏 ax1 . 换句话说,你提到的错误导致 ax1 不可见,因为不透明的 ax2 堆叠在它上面;你的代码只是堆叠在 ax2 之上的另一个轴,它仍然被"in the middle"遮住了 ax1 .

    对于你提到的bug,我们可以从the fix获得如何解决它的线索 . 尝试在代码末尾( show 之前)执行 ax2.patch.set_visible(False) . 当我这样做时,两个图都显示正确 .

相关问题