2016-06-07 302 views
3

我有更新的双轴问题。 在下面的代码中,我期望ax_hist.clear()完全清除数据,刻度和轴标签。但是当我在同一个坐标轴上再次绘图时,以前的ax_hist.hist()中的第二个y轴标签仍然存在。 如何删除旧的y轴标签?双轴的matplotlib axes.clear()不会清除第二个y轴标签

我用TkAgg和Qt5Agg进行了测试,得到了相同的结果。

import matplotlib.pyplot as plt 
import numpy as np 

fig, ax = plt.subplots() 

d1 = np.random.random(100) 
d2 = np.random.random(1000) 

ax.plot(d1) 
ax_hist = ax.twinx() 
ax_hist.hist(d1) 

ax.clear() 
ax_hist.clear() 
ax.plot(d2) 
ax_hist = ax.twinx() 
ax_hist.hist(d2) 
plt.show() 

回答

1

问题是由其中创建第一ax双轴线的第二ax_hist = ax.twinx()引起的。您只需创建一次双轴。

import matplotlib.pyplot as plt 
import numpy as np 

fig, ax = plt.subplots() 

d1 = np.random.random(100) 
d2 = np.random.random(1000) 

ax_hist = ax.twinx() # Create the twin axis, only once 

ax.plot(d1) 
ax_hist.hist(d1) 

ax.clear() 
ax_hist.clear() 

ax.plot(d2) 
ax_hist.hist(d2)