Mike Kharkov Mike Kharkov - 1 month ago 22
Python Question

Refresh of paint in Matplotlib

I have got this code:

import matplotlib
import matplotlib.pyplot as plt
from matplotlib.widgets import Slider

fig = plt.figure(figsize=(12, 6))
ax = fig.add_subplot(111)
z = plt.scatter([3,5], [1.11212,1.11215])

axcolor = '#ffffff'
ax_x_pos = plt.axes([0.086, 0.198, 0.828, 0.022], axisbg=axcolor)
x_pos = Slider(ax_x_pos, '', 0, 100, valfmt='%d',
valinit=100, color='green')

x_pos.valtext.set_visible(False)

def updateX(val):
global z
z.remove()
plt.scatter([3,5], [1.11212,1.11215])
fig.canvas.draw_idle()

cid = x_pos.on_changed(updateX)
plt.show()


How will i can draw anything after remove "Z" param?
(I got taken empty canvas(after "on_changed()") it all.)

I mean.
I need just draw some paint and then replace it with another paint.

P.S. I will be appreciate for any advice..

Answer

You define an axis, ax so plots should be drawn on that (ax.scatter instead of plt.scatter). Also, in update you don't use the slider value val to change the values you plot.

An example which changes the plot and redraws is as follows,

import matplotlib
import matplotlib.pyplot as plt
from matplotlib.widgets import Slider

fig = plt.figure(figsize=(12, 6))
ax = fig.add_subplot(111)
plt.subplots_adjust(bottom=0.25)
z = ax.scatter([3,5], [1.11212,1.11215])

axcolor = '#ffffff'
ax_x_pos = plt.axes([0.086, 0.1, 0.828, 0.022], axisbg=axcolor)
x_pos = Slider(ax_x_pos, '', 0, 100, valfmt='%d',
           valinit=100, color='green')

x_pos.valtext.set_visible(False)

def updateX(val):
    global z
    z.remove()
    z = ax.scatter([3*val/100.,5], [1.11212,1.11215*val/100.])
    fig.canvas.draw_idle()

cid = x_pos.on_changed(updateX)
plt.show()