python – twinx轴的matplotlib axes.clear()不会清除第二个y轴标签

我有一个更新的双轴的问题.

在下面的代码中,我希望ax_hist.clear()完全清除数据,刻度和轴标签.但是当我再次在相同的轴上绘制时,前一个ax_hist.hist()的第二个y轴标签仍然存在.

如何删除旧的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()

最佳答案 问题是由你的第二个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)
点赞