简体   繁体   中英

vertical colored lines on a slider matplotlib

I am building a GUI using python-tkinter module and have embedded a matplotlib bar graph using plt.figure! Here is my code:

def graph(self):
        f=plt.Figure(figsize=(40,4))
        canvas=FigureCanvasTkAgg(f,self.canvas)
        canvas.get_tk_widget().pack(side=TOP,fill=BOTH,expand=True)

        ax=f.add_subplot(111)
        f.subplots_adjust(left=0.00, right=0.99)

        self.x=range(1,100) #for example
        self.y=[1]*len(self.x)
        self.N=10
        self.f=f
        self.ax=ax

        barpos=f.add_axes([0.18, 0.03, 0.55, 0.07], facecolor='white') 
        slider=Slider(barpos, 'Plot',0,len(self.x)-self.N, valinit=0)
        self.slider=slider
        slider.on_changed(self.bar)
        self.bar(0)


    def bar(self,pos):
        pos=int(pos)
        N=self.N
        self.ax.clear()
        if pos + N > len(self.x):
            n=len(self.x)-pos
        else:
            n=N
        X=self.x[pos:pos+n]
        Y=self.y[pos:pos+n]
        self.ax.bar(X,Y,width=0.7, align='edge',color='green',alpha=0.07)
        self.ax.margins(0.01,0)


        for i,txt in enumerate(self.x):
            **self.ax.axvline(x= i, color='r')**   #*this line if I use it without embedding my plot in tkinter gives me a slider with vertical lines as shown in bottom image but if I use it in my gui code it puts the lines on the bars and not on the slider*

            self.ax.annotate(self.fid[i], (self.x[i],0.25),horizontalalignment='right',fontsize=8,color='purple',weight='bold')

        #I am annotating a bunch of stuff here 

        self.ax.axes.xaxis.set_ticks([])
        self.ax.axes.yaxis.set_ticks([])

I display 10 bars at one time and I needed help with creating vertical lines of different colors on the slider.

I was able to achieve this functionality in matplotlib where my graph is created in plt.subplots and plt.axes was used in place of f.add_axes. Can anyone help me replicate this is my tkinter slider(created using f.add_axes)? I have added an image where the top one shows how my slider looks embedded in tkinter canvas and the bottom one is from creating by using plt.axvline but same function does not work in the matplotlib figure embedded in canvas.

I want to replicate the vertical lines like in the bottom slider in the embedded plot in canvas! Any help would be really appreciated! Thanks!

slider vertical lines

The Slider resides in barpos , not in self.ax .
If you call self.ax.axvline(..) , the axvline will be inside self.ax which is the subplots with the bars. If you want to have the axvlines in the Slider axes, you need to call barpos.axvline() . Better make barpos a class variable as well and then call

self.barpos.axvline()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM