Skip to content

Instantly share code, notes, and snippets.

@fomightez
Created June 20, 2024 18:51
Show Gist options
  • Save fomightez/f2f2650f32f6e3f4b3e0c9f7f24044ab to your computer and use it in GitHub Desktop.
Save fomightez/f2f2650f32f6e3f4b3e0c9f7f24044ab to your computer and use it in GitHub Desktop.
Display the source blob
Display the rendered blob
Raw
{
"cells": [
{
"cell_type": "markdown",
"id": "b338d8a7-a977-4411-bb68-9f89af7150f1",
"metadata": {},
"source": [
"## For SO 78647857 6-20-2024 https://stackoverflow.com/q/78647857/8508004"
]
},
{
"cell_type": "code",
"execution_count": 1,
"id": "6beadc08-6104-45b1-aa24-10912880c3e5",
"metadata": {},
"outputs": [
{
"data": {
"application/vnd.jupyter.widget-view+json": {
"model_id": "eddb24d1696a4941b0c46712a828b380",
"version_major": 2,
"version_minor": 0
},
"text/plain": [
"interactive(children=(IntSlider(value=0, description='X min', step=0), IntSlider(value=0, description='X max',…"
]
},
"metadata": {},
"output_type": "display_data"
}
],
"source": [
"import pandas as pd\n",
"import numpy as np\n",
"import matplotlib.pyplot as plt\n",
"from matplotlib.collections import LineCollection\n",
"from matplotlib.colors import ListedColormap\n",
"from matplotlib.patches import Patch\n",
"from ipywidgets import interact, IntSlider, Dropdown\n",
"from ipywidgets import fixed\n",
"\n",
"df_irv = pd.DataFrame(np.random.random((100,9))*10, columns=[\"TripNumber\",\"Distance\",'Element','RHLocation','Bridge', 'Tunnel','SuspTravel', 'Roll', 'Bounce'])\n",
"df_irv['Distance'] = df_irv['Distance']*5\n",
"df_irv = df_irv.astype(int)\n",
"\n",
"tripnumber = df_irv['TripNumber'].min() + 1\n",
"\n",
"# Function to plot the data with adjustable x-axis limits\n",
"def plot_graph(xmin, xmax, Sensors, tripnumber):\n",
" \"\"\"\n",
" Plot the sensor data for a specific trip with adjustable x-axis limits, indicating where the wagon is passing through.\n",
"\n",
" Parameters:\n",
" - xmin (float): The minimum value of the x-axis (Distance).\n",
" - xmax (float): The maximum value of the x-axis (Distance).\n",
" - sensors (str): The name of the sensor data column to plot.\n",
" - tripnumber (str): The trip number to filter the data.\n",
"\n",
" Returns:\n",
" - None: Displays a plot of the sensor data with distance on the x-axis.\n",
" \"\"\"\n",
"\n",
" fig, ax = plt.subplots()\n",
"\n",
" \n",
"\n",
" # Plot the selected sensor data against distance\n",
" df_trip = df_irv[df_irv['TripNumber'] == tripnumber].reset_index(drop=True)\n",
" ax.plot('Distance', Sensors, data=df_trip)\n",
" \n",
" # Find the indices of the closest distances to xmin and xmax\n",
" id_xmin = (df_trip['Distance'] - xmin).abs().idxmin()\n",
" id_xmax = (df_trip['Distance'] - xmax).abs().idxmin()\n",
"\n",
" # Ensure that id_xmax is greater than id_xmin\n",
" if id_xmax <= id_xmin:\n",
" temp = id_xmax\n",
" id_xmax = id_xmin \n",
" id_xmin = temp\n",
"\n",
" # Create arrays for y-values and x-values within the selected range\n",
" yvals = np.full(id_xmax - id_xmin, max(df_trip[Sensors]) + 0.5)\n",
" xvals = df_trip['Distance'][id_xmin:id_xmax+1]\n",
"\n",
"\n",
" # Define colors for different elements\n",
" '''\n",
" colors = []\n",
" for i in range(id_xmin, id_xmax+1): # THIS ISN't HOW YOU'D DO THIS IN PANDAS, I don't think. But I cannot really tell purpose since no real data provided\n",
" if 'CURVA' in df_trip['Element'][i]:\n",
" colors.append('red')\n",
" elif df_trip['RHLocation'][i] == 1:\n",
" colors.append('green')\n",
" elif df_trip['Bridge'][i] == 1:\n",
" colors.append('yellow')\n",
" elif df_trip['Tunnel'][i] == 1:\n",
" colors.append('purple')\n",
" else:\n",
" colors.append('blue')\n",
" '''\n",
" colors = ['red']\n",
" \n",
" # Create line segments for the colored bands\n",
" segments = np.c_[xvals[:-1], yvals, xvals[1:], yvals].reshape(-1, 2, 2)\n",
" lines = LineCollection(segments, colors=colors)\n",
" lines.set_linewidth(20)\n",
" ax.add_collection(lines)\n",
" \n",
" # Create custom legend\n",
" legend_handles = [Patch(color='red', label='CURVA'),\n",
" Patch(color='green', label='RH'),\n",
" Patch(color='yellow', label='Bridge'),\n",
" Patch(color='purple', label='Tunnel'),\n",
" Patch(color='blue', label='Tangente')]\n",
" ax.legend(handles=legend_handles, loc='lower left', bbox_to_anchor=(1, 0.67))\n",
"\n",
" # Set the x-axis limits\n",
" #print(xmin)\n",
" #print(xmax)\n",
" #plt.xlim(xmin, xmax) # I have no idea what the purpose of this is and commenting out here since giving errors because cannot have xmin same as xmax with this\n",
" plt.xlabel('Distance (Km)')\n",
" plt.ylabel(Sensors)\n",
" plt.title(Sensors+f' vs Distance [{tripnumber}]')\n",
" plt.show()\n",
"\n",
"\n",
"\n",
"# Create sliders for x-axis limits\n",
"xmin_slider_1 = IntSlider(description='X min', step=0.5)\n",
"xmax_slider_1 = IntSlider(description='X max', step=0.5)\n",
"\n",
"# Interactive plot\n",
"interact(plot_graph,xmin = xmin_slider_1,\n",
" xmax = xmax_slider_1,\n",
" Sensors=['SuspTravel', 'Roll', 'Bounce'], \n",
" tripnumber=sorted(df_irv['TripNumber'].unique(), key = int)\n",
" );"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "f100ea00-5d8d-4533-aa2a-f0ce203980d8",
"metadata": {},
"outputs": [],
"source": []
},
{
"cell_type": "code",
"execution_count": null,
"id": "a3a72222-7d4a-40a8-be5c-e0f212900ce1",
"metadata": {},
"outputs": [],
"source": []
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3 (ipykernel)",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.10.12"
}
},
"nbformat": 4,
"nbformat_minor": 5
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment