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

标签 python matplotlib

我对更新的 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/

相关文章:

python - 使用重复键在 python 中创建嵌套字典

python - 不明白Python中将循环转换为列表的代码

Python 实现我自己的 linspace 绘图例程

python - 如何使用 pandas DataFrame 绘图函数为每个子图绘制一个 ylabel

python - matplotlib-cpp与使用C++的Visual Studio(尤其是3D图)?

python - Mechanize 浏览器超时不起作用

python - 如何从 django 框架中的表单字段中获取值(value)?

android - 如何在帧中实时加入具有 alpha/透明度的 png

python - 如何减少或以其他方式影响极坐标图中的径向刻度数?

python - 如何绘制立方体的面?