I know this is a long shot, but I have an application that would plot n spectra (counts per energy) and I want to have the option to visualise them as normal spectra or histograms.
Is there a way that I could detect which method is currently being used and use a Toggle button that would switch to the other plotting method? I’m using plt.plot for the first and plt.step for the other.
I was able to do the same thing for the x and y scales using something like this:
def toggle_xscale(self):
"""Toggle the x-axis scale between linear and logarithmic."""
current_scale = self.plot_axes.get_xscale()
new_scale = 'log' if current_scale == 'linear' else 'linear'
self.plot_axes.set_xscale(new_scale)
self.canvas.draw_idle() # Redraw the canvas
def toggle_yscale(self):
"""Toggle the y-axis scale between linear and logarithmic."""
current_scale = self.plot_axes.get_yscale()
new_scale = 'log' if current_scale == 'linear' else 'linear'
self.plot_axes.set_yscale(new_scale)
self.canvas.draw_idle() # Redraw the canvas
In my custom toolbar class from NavigationToolbar2Tk. Can anyone help?
I guess I’m expecting some similar function to the one that I showed extracting the plotting method and changing it.
Your functions are already detecting which method is currently being used. You can now simply add two buttons – and their command attrs – to call these methods.
class YourClass(tk.Tk):
def __init__(self):
super().__init__()
self.toggle_xscale_btn = tk.Button(self, text='Toggle XSCALE', command=self.toggle_xscale)
self.toggle_xscale_btn.pack()
self.toggle_yscale_btn = tk.Button(self, text='Toggle YSCALE', command=self.toggle_yscale)
self.toggle_yscale_btn.pack()
# Other self attributes and packed widgets.
def toggle_xscale(self):
"""Toggle the x-axis scale between linear and logarithmic."""
pass
def toggle_yscale(self):
"""Toggle the y-axis scale between linear and logarithmic."""
pass
1
I suggest that you keep track of the plot type, e.g., plot_type == 1
means line plot, plot_type == 0
means histogram, and
def toggle_plot_type(self, plot_type):
plot_type = 1 - plot_type
if plot_type:
# line plot
else:
# histogram
return plot_type
in the main program
type_plot = 1
# line plot
and in the interaction loop
plot_type = toggle_plot_type(plot_type)