gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 11:23:54 26 4
gpt4 key购买 nike

我对更新的 twinx 轴有疑问。在下面的代码中,我希望 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() 引起的,它创建了第一个 ax第二个双轴。您只需创建一次双轴。

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)

关于python - twinx 轴的 matplotlib axes.clear() 不清除第二个 y 轴标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37679671/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com