Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

matplotlib axes.clear() of twinx axes does not clear second y-axis label

I have an issue with updated twinx axes. In the following code, I expect that ax_hist.clear() clears data, ticks and axes labels altogether. But when I plot again in the same axes, second y-axis labels from the previous ax_hist.hist() are still there. How can I remove the old y-axis labels?

I have tested with TkAgg and Qt5Agg and got the same result.

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()
like image 778
Hoseung Choi Avatar asked Oct 31 '22 02:10

Hoseung Choi


1 Answers

The problem is caused by your second ax_hist = ax.twinx() which creates a second twin axis of the first ax. You only need to create the twin axis once.

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)
like image 180
mfitzp Avatar answered Nov 15 '22 07:11

mfitzp