I'm trying to analyze data cdf files that are automatically loaded in as tplot variables. I'm using pyspedas, a space physics python library. I've been trying to optimize my way of selecting certain time ranges of spectrograms so I can compare it to other data I have. I wanted to use spanselector to try and have a highlighted area for each graph I make, and then save the trange I selected to a list or text file, but I don't know how to make spanselector work with flux data.
All the examples I've found of spanselector are randomly generated graphs or very simple lists. I've stored the time, energy, and flux arrays into separate variables. I was able to recreate the graph using pytplot.tplot with the three separate variables, so the arrays aren't the issue. I have no idea how to plot these three variables in a way that SpanSelector can read it using matplotlib.pyplot.axes. I'm very confused and very lost and wasting more time trying to figure out this widget rather than doing actual research.
Array values for context: timedis shape: (2400,) transposedis shape: (2400, 32) engyinfodis shape: (2400, 32)
Example code here:
import matplotlib.pyplot as plt
from matplotlib.widgets import SpanSelector, Button
import pyspedas
import pytplot
%matplotlib widget
from pyspedas.mms import fgm, fpi, curlometer, mec, dsp #import instrument load routines
pytplot.del_data() #deletes previously loaded data
from pyspedas import mms, themis, cluster
from pyspedas import tinterpol #to match MEC data to OMNI 5min time stamps
from pyspedas import omni
from pyspedas import tinterpol #to match MEC data to OMNI 5min time stamps
from pyspedas import time_string # convert unix time to string(returns it as 'list object' not numpy array)
from pyspedas import time_double #convert string back to unix time
from pyspedas import cotrans #converting between coord systems (ex GSE <-> GSM)
#Spectrogram: To create a tplot variable named 'fluxes' that can be used to plot a spectrogram of electron fluxes as a function of time and energy, use store_data as follows: store_data, 'fluxes', data={x:engys.time, y:transpose(engy.data), v:engyinfo.energy}.
#For spectrograms, the x-data are times (along the x-axis of the plot), the v-data are energies (along the y-axis of the plot), and the y-data are fluxes corresponding to the color that will be plotted at each time and energy in the spectrogram.
#I realize that calling the fluxes 'y-data' is misleading, but there you have it.
def redo_selection(event):
plt.legend()
span.reset()
# Define a function to be called on region selection
def onselect(xmin, xmax):
trange = {'start_time': xmin, 'end_time': xmax}
selected_tranges.append(trange)
print(f"Selected trange: {xmin} to {xmax}")
def selectevents(first_dt, last_dt):
data = pyspedas.mms.fpi(trange=[first_dt, last_dt], time_clip=True, data_rate='fast')
data2 = pyspedas.mms.eis(trange=[first_dt, last_dt], time_clip=True, datatype='extof', probe=['1','2','3','4'])
timedis = get_data('mms1_dis_energyspectr_omni_fast').times
transposedis = get_data('mms1_dis_energyspectr_omni_fast').y
engyinfodis = get_data('mms1_dis_energyspectr_omni_fast').v
# Initialize variables to store selected trange
selected_tranges = []
# Create the SpanSelector
fig, ax = plt.subplots()
span = SpanSelector(
ax,
onselect,
"horizontal",
useblit=True,
props=dict(alpha=0.5, facecolor="tab:blue"),
interactive=True,
drag_from_anywhere=True
)
# options('ionflux', 'spec', True)
# options('ionflux', 'ylog', True)
# options('ionflux', 'zlog', True)
# Plot ionflux spectrogram as a color bar
# pytplot.tplot('ionflux')
# Plot electronflux spectrogram as a color bar
# pytplot.tplot('electronflux')
cbar = plt.colorbar(mesh, ax=ax, label='Flux')
# Create buttons for redoing and confirming the selection
ax_redo = plt.axes([0.8, 0.01, 0.1, 0.05])
ax_confirm = plt.axes([0.6, 0.01, 0.1, 0.05])
btn_redo = Button(ax_redo, 'Redo')
btn_redo.on_clicked(redo_selection) # Define redo_selection function if needed
btn_confirm = Button(ax_confirm, 'Confirm')
btn_confirm.on_clicked(confirm_selection) # Define confirm_selection function if needed
def confirm_selection(event):
if selected_tranges:
# Save the selected tranges to a file or process them as needed
with open("path/to/file.rtf", "w") as file:
for trange in selected_tranges:
file.write(f"{trange['start_time']} to {trange['end_time']}\n")
print("Selected tranges saved successfully.")
else:
print("No tranges selected.")
# Save the selected tranges to a list
for trange in selected_tranges:
print(f"{trange['start_time']} to {trange['end_time']}")
# Save the selected region as a PNG file with trange information for all variables
if start_time is not None and end_time is not None:
pytplot.savefig(filename=upstream{first_dt}.png")
print(f"Selected trange: {start_time} to {end_time}")
else:
print("No trange selected.")