How can I get figure to refresh after changing an object's axes in Matplotlib?

StackOverflow https://stackoverflow.com/questions/7117248

  •  01-01-2021
  •  | 
  •  

Pregunta

Please refer to the example below. Two subplots are added, and to each a Line2D plot is inserted. I then change the Line2D's axes in the second subplot to be the first subplot. Judging by the get_geometry output this is successful. However in the actual figure the two Line2D plots are still in their original subplots.

What am I missing here? How can I refresh the figure to reflect the axes change?

Obviously this is a fairly moronic example, the real application is more of a dynamic nature.

Script:

import matplotlib.pyplot as plt

fig = plt.figure()  
ax_1 = fig.add_subplot(2,1,1)
ax_2 = fig.add_subplot(2,1,2)
ax_1.plot([0,1,2],[0,1,2])
ax_2.plot([0,1,2],[2,1,0])

print 'before'
for line in ax_1.get_lines():
    print line.get_ydata()
    print line.get_axes().get_geometry()
    print id(line.get_axes())

for line in ax_2.get_lines():
    print line.get_ydata()
    print line.get_axes().get_geometry()
    print id(line.get_axes())

f = ax_2.get_lines()[0]
f.set_axes(ax_1)

print 'after'
for line in ax_1.get_lines():
    print line.get_ydata()
    print line.get_axes().get_geometry()
    print id(line.get_axes())

for line in ax_2.get_lines():
    print line.get_ydata()
    print line.get_axes().get_geometry()
    print id(line.get_axes())

plt.show()

Output:

before
[0 1 2]
(2, 1, 1)
4330504912
[2 1 0]
(2, 1, 2)
4336262288
after
[0 1 2]
(2, 1, 1)
4330504912
[2 1 0]
(2, 1, 1)
4330504912

Figure output: Figure

¿Fue útil?

Solución 2

Later on I posted the same question here, and this was the response.

TL,DR It's not supported.

Otros consejos

I believe that one problem is that your first axes (ax_1) do not have the line that you want to add (f) in their list of lines (ax_1.lines).

You can "copy" the line from the second plot to the first one with

f = ax_2.lines.pop()  # Removes the line from the second plot
ax_1.plot(*f.get_data())  # Draws a new line in the first plot, but with the coordinates of the second line

(with this method, there is obviously no need to do f.set_axes(ax_1)). Other arguments to plot() could be used in order to also copy the color, etc., I guess.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top