简体   繁体   中英

How to use the slider to update more line plots at the same time?

this is my first question code related, so please bear with me I'm a complete beginner,I've developed a small desktop app using three libraries (tkiner, pandas and matplotlib). this app plots several graphs from a csv.One of these graphs is dynamically updated using a slider that changes a factor by which the x value is multiplied.

My question is: how can I change also the legend at the same time as well as the limit of my x-axis?

I was trying to access the labels of ax2 and assign them the updated value, but I couldn't find a way to do that. Is there something like l.set_label(label=name +" Nspt x f1={}".format(f1)) ?

I attach a small code section that shows the problem. Also an image of the plot. thanks in advace to who will spend his time helping me.

initial_f1=5

axcolor ='darkgray'
axf1 = plt.axes([0.6,0.01, 0.3, 0.01], facecolor=axcolor)
sf1=Slider(axf1,"f1",4.0,6.5,valinit=initial_f1,valstep=0.5)

for name, group in bh_groups:
    ax1.plot(group["Nspt"],group["ztest"],marker="X",linestyle="",ms=8, label=name)
    ax2.plot(group["cu"],group["ztest"],marker="o",linestyle="",ms=8,label=name +" Triaxial tests")
    l,=ax2.plot(group["Nspt"]*initial_f1,group["ztest"],marker="X",linestyle="",ms=8,label=name +" Nspt x f1={}".format(initial_f1))
 

    def update(val):

        f1 = sf1.val
        l.set_xdata(f1*group["Nspt"])                
        fig1.canvas.draw_idle()
        
    sf1.on_changed(update)



ax1.set_xlabel('Nspt',fontweight="bold")    
ax1.xaxis.set_label_position('top')
ax1.xaxis.tick_top()
ax1.set_ylabel("z [mOD]")

ax2.set_xlabel('Undrained Shear Strength, su [kPa]',fontweight="bold")    
ax2.xaxis.set_label_position('top')
ax2.xaxis.tick_top()
ax2.set_ylabel("z [mOD]")

Output:

在此处输入图像描述

EDITED: I managed to updated the legend as well, now what if I want the slider to act on more lines at the same time? the lines are described by a fuction and depend on the same variable f1. I haven't found a solution for this, any idea?

fig1, (ax1,ax2) = plt.subplots(nrows=1,ncols=2)
fig1.canvas.set_window_title('Data by borehole')

initial_f1=5

axcolor ='darkgray'
axf1 = plt.axes([0.6,0.01, 0.3, 0.01], facecolor=axcolor)
sf1=Slider(axf1,"f1",4.0,6.5,valinit=initial_f1,valstep=0.5)


   
for name, group in bh_groups:
    ax1.plot(group["Nspt"],group["ztest"],marker="X",linestyle="",ms=8, label=name)
    ax2.plot(group["cu"],group["ztest"],marker="o",linestyle="",ms=8,label=name +" Triaxial tests")
    
    l,=ax2.plot(group["Nspt"]*initial_f1,group["ztest"],marker="X",linestyle="",ms=8,label=name +" Nspt x f1={}".format(initial_f1))
    




def update(val):
    f1 = val
   
    l.set_xdata(f1*group["Nspt"])  
            
    l.set_label(name +" Nspt x f1={}".format(f1)) 
    ax2.legend(loc="best")
        
sf1.on_changed(update)
fig1.canvas.draw_idle()
    

ax1.set_xlabel('Nspt',fontweight="bold")    
ax1.xaxis.set_label_position('top')
ax1.xaxis.tick_top()
ax1.set_ylabel("z [mOD]")

ax2.set_xlabel('Undrained Shear Strength, su [kPa]',fontweight="bold")    
ax2.xaxis.set_label_position('top')
ax2.xaxis.tick_top()
ax2.set_ylabel("z [mOD]")

ax1.legend(loc="best") 

plt.tight_layout()

 

plt.show()

在此处输入图像描述

Here is a simple example, where one slider controls:

  • two lines
  • two labels + legend entries
  • the limits of the x-axis

The two functions are not very creative: y1=sin(alpha*x) and y2=cos(alpha*x) and the limits on the x axis are: [0, 3*pi*alpha]

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

x = np.linspace(0, np.pi * 2, 1000)
y1 = np.sin(1*x)
y2 = np.cos(1*x)

fig, ax = plt.subplots()
fig.subplots_adjust(bottom=0.25)
ax.set_xlim(0, 2*np.pi)
h1 = ax.plot(x, y1, label='dummy')[0]
h2 = ax.plot(x, y2, label='dummy')[0]

ax.legend(loc='upper right')
slider_alpha = Slider(plt.axes([0.2, 0.1, 0.6, 0.05]), 'alpha',
                      valmin=1, valmax=2, valinit=1, valstep=0.01)

def update(val):
    # Update lines 
    x = np.linspace(0, np.pi*3*val, 1000)
    y1 = np.sin(x*val)
    y2 = np.cos(x*val)
    h1.set_data(x, y1)
    h2.set_data(x, y2)
   
    # Update labels + legend()
    h1.set_label("y=sin(x*{:.3})".format(float(val)))
    h2.set_label("y=cos(x*{:.3})".format(float(val)))
    ax.legend(loc='upper right')
    
    # Update x limits
    ax.set_xlim(0, np.pi*3*val)

slider_alpha.on_changed(update)

在此处输入图像描述

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