Manuel
Manuel

Reputation: 17

update bar chart using a slider in matplotlib

I try to make a simple bar chart, where I can monitor a chemical reaction ( A -> B) using a slider for reaction steps. So far, the following code yields a bar chart for A with a slider for reactionsteps. The print function prints the expected values for A after certain reaction steps. However, the plot won't be updated. I tried plt.draw(), plt.show() and fig.canvas.draw() but none of them worked.

import matplotlib.pyplot as plt
import numpy as np
from matplotlib.widgets import Slider, Button

fig, ax = plt.subplots()
plt.subplots_adjust(bottom=0.25)
fig.canvas.set_window_title('Einfluss der Geschwindigkeitskonstanten')

a0 = 1
b0 = 0
plt.axis([0, 5, 0, 2])
plt.xticks([1, 4], ['A', 'B'])
plt.bar(1, a0, color = 'red')

#slider:
axcolor = 'lightblue'
axrs = plt.axes([0.25, 0.1, 0.65, 0.03], facecolor=axcolor)
srs = Slider(axrs, 'RS', 0, 20, valinit=0)

def slider_val_fkt(t):
    ya = []
    t = srs.val
    ya = [np.exp(-0.6 * t)]
    print(ya)
    plt.bar(1, ya, color = 'red')
    #plt.draw()
    #plt.show()
    fig.canvas.draw()

srs.on_changed(slider_val_fkt)

plt.show()

Upvotes: 1

Views: 2117

Answers (1)

ImportanceOfBeingErnest
ImportanceOfBeingErnest

Reputation: 339430

The new bar is drawn inside the slider axes instead of the original axes: enter image description here

To overcome this you should work on the axes objects instead of using pyplot. However, since you anyways want to update the bar instead of drawing a new one, it is sufficient here to work with the bars themselves and update them using set_height.

bars = plt.bar(1, a0, color = 'red')

axrs = plt.axes([0.25, 0.1, 0.65, 0.03], facecolor='lightblue')
srs = Slider(axrs, 'RS', 0, 20, valinit=0)

def slider_val_fkt(t):
    t = srs.val
    ya = [np.exp(-0.6 * t)]
    bars[0].set_height(ya[0])
    fig.canvas.draw_idle()

srs.on_changed(slider_val_fkt)

Upvotes: 1

Related Questions