T

#### Tiago Amorim

##### Guest

Here is the code I'm using:

Code:

```
# Function to plot the data with adjustable x-axis limits
def plot_graph(xmin, xmax, Sensors, tripnumber):
"""
Plot the sensor data for a specific trip with adjustable x-axis limits, indicating where the wagon is passing through.
Parameters:
- xmin (float): The minimum value of the x-axis (Distance).
- xmax (float): The maximum value of the x-axis (Distance).
- sensors (str): The name of the sensor data column to plot.
- tripnumber (str): The trip number to filter the data.
Returns:
- None: Displays a plot of the sensor data with distance on the x-axis.
"""
fig, ax = plt.subplots()
# Filter the data by the selected trip number
df_trip = df_irv[df_irv['TripNumber'] == tripnumber].reset_index(drop=True)
# Plot the selected sensor data against distance
ax.plot('Distance', Sensors, data=df_trip)
# Find the indices of the closest distances to xmin and xmax
id_xmin = (df_trip['Distance'] - xmin).abs().idxmin()
id_xmax = (df_trip['Distance'] - xmax).abs().idxmin()
# Ensure that id_xmax is greater than id_xmin
if id_xmax <= id_xmin:
temp = id_xmax
id_xmax = id_xmin
id_xmin = temp
# Create arrays for y-values and x-values within the selected range
yvals = np.full(id_xmax - id_xmin, max(df_trip[Sensors]) + 0.5)
xvals = df_trip['Distance'][id_xmin:id_xmax+1]
# Define colors for different elements
colors = []
for i in range(id_xmin, id_xmax+1):
if 'CURVA' in df_trip['Element'][i]:
colors.append('red')
elif df_trip['RHLocation'][i] == 1:
colors.append('green')
elif df_trip['Bridge'][i] == 1:
colors.append('yellow')
elif df_trip['Tunnel'][i] == 1:
colors.append('purple')
else:
colors.append('blue')
# Create line segments for the colored bands
segments = np.c_[xvals[:-1], yvals, xvals[1:], yvals].reshape(-1, 2, 2)
lines = LineCollection(segments, colors=colors)
lines.set_linewidth(20)
ax.add_collection(lines)
# Create custom legend
legend_handles = [Patch(color='red', label='CURVA'),
Patch(color='green', label='RH'),
Patch(color='yellow', label='Bridge'),
Patch(color='purple', label='Tunnel'),
Patch(color='blue', label='Tangente')]
ax.legend(handles=legend_handles, loc='lower left', bbox_to_anchor=(1, 0.67))
# Set the x-axis limits
plt.xlim(xmin, xmax)
plt.xlabel('Distance (Km)')
plt.ylabel(Sensors)
plt.title(Sensors+f' vs Distance [{tripnumber}]')
plt.show()
# Update sliders when trip is selected
def update_sliders(tripnumber):
"""
Update the range and values of the x-axis limit sliders based on the selected trip number.
Parameters:
- tripnumber (str): The selected trip number.
Returns:
- None
"""
# Filter the data for the selected trip number
df_trip = df_irv[df_irv['TripNumber'] == tripnumber]
# Get the minimum and maximum distances for the selected trip
min_distance = df_trip['Distance'].min()
max_distance = df_trip['Distance'].max()
try:
# Update the slider ranges and values
xmax_slider_1.max = max_distance
xmax_slider_1.min = min_distance + 1
xmin_slider_1.max = max_distance - 1
xmin_slider_1.min = min_distance
xmax_slider_1.value = max_distance
xmin_slider_1.value = min_distance
# This excetion is because I kept getting TraitError for 'setting max<min'
except:
# Update the slider ranges and values
xmax_slider_1.min = min_distance + 1
xmax_slider_1.max = max_distance
xmin_slider_1.min = min_distance
xmin_slider_1.max = max_distance - 1
xmax_slider_1.value = max_distance
xmin_slider_1.value = min_distance
# Create dropdown for trip selection
tripnumber_dropdown = Dropdown(options=sorted(df_irv['TripNumber'].unique(), key = int), description='TripNumber')
# Create sliders for x-axis limits
xmin_slider_1 = IntSlider(description='X min', step=0.5)
xmax_slider_1 = IntSlider(description='X max', step=0.5)
# Update sliders based on the initial trip number value
update_sliders(tripnumber_dropdown.value)
# Observe changes in the trip number dropdown and call on_tripnumber_change function
tripnumber_dropdown.observe(on_tripnumber_change, names='value')
# Interactive plot
interact(plot_graph,xmin = xmin_slider_1,
xmax = xmax_slider_1,
Sensors=['SuspTravel', 'Roll', 'Bounce'],
tripnumber=tripnumber_dropdown)
```

<a href="https://i.sstatic.net/2GT2jqM6.png" rel="nofollow noreferrer">Ploted graph</a>

<a href="https://i.sstatic.net/ZaLfG6mS.png" rel="nofollow noreferrer">Problem that has occurred</a></p>

<p>Here is the code I'm using:</p>

<pre><code># Function to plot the data with adjustable x-axis limits

def plot_graph(xmin, xmax, Sensors, tripnumber):

"""

Plot the sensor data for a specific trip with adjustable x-axis limits, indicating where the wagon is passing through.

Parameters:

- xmin (float): The minimum value of the x-axis (Distance).

- xmax (float): The maximum value of the x-axis (Distance).

- sensors (str): The name of the sensor data column to plot.

- tripnumber (str): The trip number to filter the data.

Returns:

- None: Displays a plot of the sensor data with distance on the x-axis.

"""

fig, ax = plt.subplots()

# Filter the data by the selected trip number

df_trip = df_irv[df_irv['TripNumber'] == tripnumber].reset_index(drop=True)

# Plot the selected sensor data against distance

ax.plot('Distance', Sensors, data=df_trip)

# Find the indices of the closest distances to xmin and xmax

id_xmin = (df_trip['Distance'] - xmin).abs().idxmin()

id_xmax = (df_trip['Distance'] - xmax).abs().idxmin()

# Ensure that id_xmax is greater than id_xmin

if id_xmax <= id_xmin:

temp = id_xmax

id_xmax = id_xmin

id_xmin = temp

# Create arrays for y-values and x-values within the selected range

yvals = np.full(id_xmax - id_xmin, max(df_trip[Sensors]) + 0.5)

xvals = df_trip['Distance'][id_xmin:id_xmax+1]

# Define colors for different elements

colors = []

for i in range(id_xmin, id_xmax+1):

if 'CURVA' in df_trip['Element']

*:*

colors.append('red')

elif df_trip['RHLocation']

colors.append('red')

elif df_trip['RHLocation']

*== 1:*

colors.append('green')

elif df_trip['Bridge']colors.append('green')

elif df_trip['Bridge']

*== 1:*

colors.append('yellow')

elif df_trip['Tunnel']colors.append('yellow')

elif df_trip['Tunnel']

*== 1:*

colors.append('purple')

else:

colors.append('blue')

# Create line segments for the colored bands

segments = np.c_[xvals[:-1], yvals, xvals[1:], yvals].reshape(-1, 2, 2)

lines = LineCollection(segments, colors=colors)

lines.set_linewidth(20)

ax.add_collection(lines)

# Create custom legend

legend_handles = [Patch(color='red', label='CURVA'),

Patch(color='green', label='RH'),

Patch(color='yellow', label='Bridge'),

Patch(color='purple', label='Tunnel'),

Patch(color='blue', label='Tangente')]

ax.legend(handles=legend_handles, loc='lower left', bbox_to_anchor=(1, 0.67))

# Set the x-axis limits

plt.xlim(xmin, xmax)

plt.xlabel('Distance (Km)')

plt.ylabel(Sensors)

plt.title(Sensors+f' vs Distance [{tripnumber}]')

plt.show()

# Update sliders when trip is selected

def update_sliders(tripnumber):

"""

Update the range and values of the x-axis limit sliders based on the selected trip number.

Parameters:

- tripnumber (str): The selected trip number.

Returns:

- None

"""

# Filter the data for the selected trip number

df_trip = df_irv[df_irv['TripNumber'] == tripnumber]

# Get the minimum and maximum distances for the selected trip

min_distance = df_trip['Distance'].min()

max_distance = df_trip['Distance'].max()

try:

# Update the slider ranges and values

xmax_slider_1.max = max_distance

xmax_slider_1.min = min_distance + 1

xmin_slider_1.max = max_distance - 1

xmin_slider_1.min = min_distance

xmax_slider_1.value = max_distance

xmin_slider_1.value = min_distance

# This excetion is because I kept getting TraitError for 'setting max<min'

except:

# Update the slider ranges and values

xmax_slider_1.min = min_distance + 1

xmax_slider_1.max = max_distance

xmin_slider_1.min = min_distance

xmin_slider_1.max = max_distance - 1

xmax_slider_1.value = max_distance

xmin_slider_1.value = min_distance

# Create dropdown for trip selection

tripnumber_dropdown = Dropdown(options=sorted(df_irv['TripNumber'].unique(), key = int), description='TripNumber')

# Create sliders for x-axis limits

xmin_slider_1 = IntSlider(description='X min', step=0.5)

xmax_slider_1 = IntSlider(description='X max', step=0.5)

# Update sliders based on the initial trip number value

update_sliders(tripnumber_dropdown.value)

# Observe changes in the trip number dropdown and call on_tripnumber_change function

tripnumber_dropdown.observe(on_tripnumber_change, names='value')

# Interactive plot

interact(plot_graph,xmin = xmin_slider_1,

xmax = xmax_slider_1,

Sensors=['SuspTravel', 'Roll', 'Bounce'],

tripnumber=tripnumber_dropdown)

</code></pre>colors.append('purple')

else:

colors.append('blue')

# Create line segments for the colored bands

segments = np.c_[xvals[:-1], yvals, xvals[1:], yvals].reshape(-1, 2, 2)

lines = LineCollection(segments, colors=colors)

lines.set_linewidth(20)

ax.add_collection(lines)

# Create custom legend

legend_handles = [Patch(color='red', label='CURVA'),

Patch(color='green', label='RH'),

Patch(color='yellow', label='Bridge'),

Patch(color='purple', label='Tunnel'),

Patch(color='blue', label='Tangente')]

ax.legend(handles=legend_handles, loc='lower left', bbox_to_anchor=(1, 0.67))

# Set the x-axis limits

plt.xlim(xmin, xmax)

plt.xlabel('Distance (Km)')

plt.ylabel(Sensors)

plt.title(Sensors+f' vs Distance [{tripnumber}]')

plt.show()

# Update sliders when trip is selected

def update_sliders(tripnumber):

"""

Update the range and values of the x-axis limit sliders based on the selected trip number.

Parameters:

- tripnumber (str): The selected trip number.

Returns:

- None

"""

# Filter the data for the selected trip number

df_trip = df_irv[df_irv['TripNumber'] == tripnumber]

# Get the minimum and maximum distances for the selected trip

min_distance = df_trip['Distance'].min()

max_distance = df_trip['Distance'].max()

try:

# Update the slider ranges and values

xmax_slider_1.max = max_distance

xmax_slider_1.min = min_distance + 1

xmin_slider_1.max = max_distance - 1

xmin_slider_1.min = min_distance

xmax_slider_1.value = max_distance

xmin_slider_1.value = min_distance

# This excetion is because I kept getting TraitError for 'setting max<min'

except:

# Update the slider ranges and values

xmax_slider_1.min = min_distance + 1

xmax_slider_1.max = max_distance

xmin_slider_1.min = min_distance

xmin_slider_1.max = max_distance - 1

xmax_slider_1.value = max_distance

xmin_slider_1.value = min_distance

# Create dropdown for trip selection

tripnumber_dropdown = Dropdown(options=sorted(df_irv['TripNumber'].unique(), key = int), description='TripNumber')

# Create sliders for x-axis limits

xmin_slider_1 = IntSlider(description='X min', step=0.5)

xmax_slider_1 = IntSlider(description='X max', step=0.5)

# Update sliders based on the initial trip number value

update_sliders(tripnumber_dropdown.value)

# Observe changes in the trip number dropdown and call on_tripnumber_change function

tripnumber_dropdown.observe(on_tripnumber_change, names='value')

# Interactive plot

interact(plot_graph,xmin = xmin_slider_1,

xmax = xmax_slider_1,

Sensors=['SuspTravel', 'Roll', 'Bounce'],

tripnumber=tripnumber_dropdown)

</code></pre>