Matplotlib:使用twinx()和cla()清除秒后不能重新绘制第一个轴

时间:2014-11-30 18:44:25

标签: python matplotlib plot

我对第二轴有一个奇怪的问题......不确定我是否做错了。

来自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

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

clear first axis

如果我在绘制之前通过在ax2.cla()之前添加plt.show()来清除第二个轴,则会清除两个轴。不完全符合预期,但似乎是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 个答案:

答案 0 :(得分:2)

我认为问题在于您通过再次调用ax2来创建 twinx。但是最初的孪生轴仍然存在,并且由于你提到的错误,它设置为不透明,所以它仍然隐藏ax1。换句话说,您提到的错误导致ax1不可见,因为不透明的ax2堆叠在它上面;你的代码只是在ax2之上堆叠另一个轴,这仍然会使ax1被轴遮挡,并且#34;在中间"。

对于您提到的错误,我们可以从the fix获取有关如何修复它的线索。尝试在代码末尾(ax2.patch.set_visible(False)之前)执行show。当我这样做时,两个图都会正确显示。