View 3 dimensional Numpy array in Matplotlib and taking arguments from Keyboard or mouse

2024/7/5 11:32:02

I have 3 dimensional data say (5,100,100). Now I would like to see them slice by slice upon hitting the down arrow button.

Answer

I adapted the code from an answer I gave to this question a couple of weeks ago to include keystrokes. The left key will scroll backwards, the right key will scroll forwards.

import matplotlib.widgets
import matplotlib.patches
import mpl_toolkits.axes_grid1class PageSlider(matplotlib.widgets.Slider):def __init__(self, ax, label, numpages = 10, valinit=0, valfmt='%1d', closedmin=True, closedmax=True,  dragging=True, **kwargs):self.facecolor=kwargs.get('facecolor',"w")self.activecolor = kwargs.pop('activecolor',"b")self.fontsize = kwargs.pop('fontsize', 10)self.numpages = numpagesself.fig = ax.figuresuper(PageSlider, self).__init__(ax, label, 0, numpages, valinit=valinit, valfmt=valfmt, **kwargs)self.poly.set_visible(False)self.vline.set_visible(False)self.pageRects = []for i in range(numpages):facecolor = self.activecolor if i==valinit else self.facecolorr  = matplotlib.patches.Rectangle((float(i)/numpages, 0), 1./numpages, 1, transform=ax.transAxes, facecolor=facecolor)ax.add_artist(r)self.pageRects.append(r)ax.text(float(i)/numpages+0.5/numpages, 0.5, str(i+1),  ha="center", va="center", transform=ax.transAxes,fontsize=self.fontsize)self.valtext.set_visible(False)divider = mpl_toolkits.axes_grid1.make_axes_locatable(ax)bax = divider.append_axes("right", size="5%", pad=0.05)fax = divider.append_axes("right", size="5%", pad=0.05)self.button_back = matplotlib.widgets.Button(bax, label=ur'$\u25C0$', color=self.facecolor, hovercolor=self.activecolor)self.button_forward = matplotlib.widgets.Button(fax, label=ur'$\u25B6$', color=self.facecolor, hovercolor=self.activecolor)self.button_back.label.set_fontsize(self.fontsize)self.button_forward.label.set_fontsize(self.fontsize)self.button_back.on_clicked(self.backward)self.button_forward.on_clicked(self.forward)#connect keys:self.fig.canvas.mpl_connect('key_press_event', self.keyevent)def _update(self, event):super(PageSlider, self)._update(event)i = int(self.val)if i >=self.valmax:returnself._colorize(i)def _colorize(self, i):for j in range(self.numpages):self.pageRects[j].set_facecolor(self.facecolor)self.pageRects[i].set_facecolor(self.activecolor)def forward(self, event):current_i = int(self.val)i = current_i+1if (i < self.valmin) or (i >= self.valmax):returnself.set_val(i)self._colorize(i)def backward(self, event):current_i = int(self.val)i = current_i-1if (i < self.valmin) or (i >= self.valmax):returnself.set_val(i)self._colorize(i)# define keyevent, left: backwards, right: forwardsdef keyevent(self, event):#print event.keyif event.key == 'right':self.forward(event)if event.key == 'left':self.backward(event)self.fig.canvas.draw()if __name__ == "__main__":import numpy as npfrom matplotlib import pyplot as pltnum_pages = 5data = np.random.rand(num_pages, 100, 100)fig, ax = plt.subplots()fig.subplots_adjust(bottom=0.18)im = ax.imshow(data[0, :, :], cmap='viridis', interpolation='nearest')ax_slider = fig.add_axes([0.1, 0.05, 0.8, 0.04])slider = PageSlider(ax_slider, 'Page', num_pages, activecolor="orange")def update(val):i = int(slider.val)im.set_data(data[i, :,:])slider.on_changed(update)plt.show()
https://en.xdnf.cn/q/119532.html

Related Q&A

python default argument syntax error

I just wrote a small text class in python for a game written using pygame and for some reason my default arguments arent working. I tried looking at the python documentation to see if that might give m…

Variable not defined (Python)

FlightType=input("Which flight would you like to fly? Type 2 Seater, 4 Seater, or Historic.") # No validation included for the inputFlightLen=input("Would you like to book the 30 minu…

PyGame: draw.rect() has invalid parameters

Im trying to learn mouse events with PyGame, and Im trying to draw a box wherever the user clicks. Im setting a variable equal to pygame.mouse.get_pos(), and calling individual tuple members according …

Cant press enter in selenium2library

Im trying to make a test that will open Facebook, log in and search something. However Im having trouble getting Facebook to search. Selenium types whatever it needs in the search bar, but I cant find …

Converting string to datetime in Python using strptime

Im trying to convert the following String to datetime object in Python.datetime_object = datetime.strptime(Sat, 26 Nov 2016 15:17:00 +0000, %a, %b %d %Y %H:%c %z)I get the following error,File "&l…

Is there any differences between python2 and python3 about adding menu bar to Frame in tkinter?

Im trying to porting a project 2to3 on python, and stuck in tkinter.In python2, there is no problem with adding menu bar to Frame in tkinter,but python3 occured attribute error. (Frame object has no at…

Standard Input having weird characters with them in different programming lanuage

I am getting confused with the standard input of these programming languages : [Note:] I added details about so many programming languages as the problem with all of them is same in this matter and my …

How to turn a numpy array to a numpy object?

I have a NumPy array as follows: [[[ 0 0]][[ 0 479]][[639 479]][[639 0]]]and I would like to convert it into something like so: [( 0 0)( 0 479)(639 479)(639 0), dtype=dtype([(x, <i2), (y…

recover all line from an attribute in a database in json

To simplify my problem, I have a base in json, and I recover all of my lines of json to put informations in a base. It seems easy for moments, but problem is that my json is not correctly writtenSo i…

Calculate eigen value in python as same way(order) in Matlab

This is the Matlab code which is returning eigenvector in V and eigenvalue in D. Consider C is 9*9 matrix then V is 9*9 matrix and D is 9*9 diagonal. matrix.[V,D] = eig(C);I want the same thing in Pyth…