0

I have a barplot with 20 labels and corresponding values, which is embedded on a tkinter figure canvas. A slider enables the user to view 5 bar values at a time. Adapting the approach at Python: Embed a matplotlib plot with slider in tkinter properly I have the following:

import random
import numpy as np
import matplotlib
import tkinter as Tk
import matplotlib.pyplot as plt
from matplotlib.widgets import Slider
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg

matplotlib.use('TkAgg')

root = Tk.Tk()
root.wm_title("Barplot with slider")

fig = plt.Figure()
canvas = FigureCanvasTkAgg(fig, root)
canvas.draw()
canvas.get_tk_widget().pack(side=Tk.TOP, fill=Tk.BOTH, expand=1)

channels=
['a','b','c','d','e','f','g','h','i','j','k','m','n','o','p','q','r','s','t','u']

X=range(len(channels))
Y=np.random.randint(0,100, len(X))
M=max(Y)

N=5

ax=fig.add_subplot(111)
ax.axis([0, N, 0,M])

ax.set_xticks(range(len(channels)))
ax.set_xticklabels(channels)
fig.subplots_adjust(bottom=0.25)

ax.bar(X,Y,width=0.7,align='center',color='green',ecolor='black')

ax_time = fig.add_axes([0.12, 0.1, 0.78, 0.03])
s_time = Slider(ax_time, 'Channels', 0, len(X)-N, valinit=0,valstep=1)


def update(val):
    N=5
    pos = s_time.val
    ax.axis([pos-1/2, pos+N-1/2, 0,M+1])
    fig.canvas.draw_idle()

s_time.on_changed(update)

Tk.mainloop()

It works fine, but there's one little thing I find annoying. When one runs the module, the first thing to appear is a barplot showing all 20 bars. I don't want that, as it is aesthetically unpleasing if I have a large number of bars.

Instead, I want the very first plot to appear on my canvas consist of only the first 5 bars labelled, 'a','b','c','d','e'.

1 Answer 1

1

Since you already have your update function setup, simply set the default value to 0:

...

s_time.on_changed(update)
s_time.set_val(0)

root.mainloop()
Sign up to request clarification or add additional context in comments.

1 Comment

Such a simple solution--Thanks! (Annoying the SF makes me wait at least 5-10 minutes before accepting an answer.)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.