def _bind_mouse_events_to_canvas(axes: Axes3D, canvas: FigureCanvasBase): axes.mouse_init() # Event binding was possible through mouse_init() up to matplotlib 3.2. # In 3.3.0 this was moved, so we are forced to do it here. if mpl.__version__ >= "3.3.0": canvas.mpl_connect("button_press_event", axes._button_press) canvas.mpl_connect("button_release_event", axes._button_release) canvas.mpl_connect("motion_notify_event", axes._on_move)
def addmpl(self, fig): self.fig = fig self.canvas = FigureCanvas(fig) self.mplvl.addWidget(self.canvas) self.canvas.draw() self.toolbar = NavigationToolbar(self.canvas, self.mplwindow, coordinates=True) self.mplvl.addWidget(self.toolbar) ax = fig.get_axes()[0] Axes3D.mouse_init(ax)
def __init__(self, *values, is_synchronised=True): self.figure = Figure() self.axes = list() self.lines = dict() self.__data = dict() self.__highlight_points = dict() self.__highlight_sections = dict() self.is_synchronised = is_synchronised self.addSubplots(*values) MatplotlibDrawingArea.__init__(self, self.figure) for subplot in self.axes: Axes3D.mouse_init(subplot) self.connect('notify::highlight-point', self.updateHighlightPoint) self.figure.canvas.mpl_connect('motion_notify_event', self.onMove)
def plot_3d(self, z_data, x_coverage, y_coverage, title=None, x_axis_label="X", y_axis_label="Y", z_axis_label="Z"): # 3D plotting is sort of a pain in the neck, and heavily dependent on data formatting. This routine assumes that you are # providing the z height data as a two dimensional array array, and that the overall X and Y spans are # given, so the routine can automatically compute arrays comprising the X and Y positions. If your data files contain the X and Y # positions explicitly, this routine AND the data file reader will require heavy modification to ensure that the data gets # passed and plotted correctly. # takes Z data as an X by Y array of z values, and computes the X and Y arrays based on the "coverage" provided and the size # of the Z array # \todo design a better way of handling x and y coordinates # these might be passed as strings by the config parser, so ensure that they are recast as integers # \todo use configobj validators to handle this casting x_coverage = int(x_coverage) y_coverage = int(y_coverage) z_data = npy.array(z_data) self.clear_figure() # set up some borders # these borders never go away, and screw up the other plots - leave them out until a better way is found to elegently fix them # self.fig.subplots_adjust(left=0.05) # self.fig.subplots_adjust(right=0.95) # self.fig.subplots_adjust(top=0.97) # self.fig.subplots_adjust(bottom = 0.03) axes = self.fig.add_subplot(111, projection="3d") # allow us to use the mouse to spin the 3d plot around Axes3D.mouse_init(axes) (x_data, y_data) = compute_3d_coordinates(z_data, x_coverage, y_coverage) axes.plot_wireframe(x_data, y_data, z_data) if title: axes.set_title(title) axes.set_xlabel(x_axis_label) axes.set_ylabel(y_axis_label) axes.set_zlabel(z_axis_label) axes.view_init(self.elev_3d, self.azim_3d) self.canvas.draw() self.current_plot_type = "3D"
def add_mpl_figure(self, fig): self.mpl_canvas = FigureCanvasTkAgg(fig, self) #self.mpl_canvas.show() self.mpl_canvas.get_tk_widget().pack(side=tk.TOP, fill=tk.BOTH, expand=True) #adds toolbar - self.toolbar = NavigationToolbar2Tk( self.mpl_canvas, self) #sometimes also NavigationToolbar2TkAgg self.toolbar.update() ax = fig.get_axes()[0] Axes3D.mouse_init(ax) # enable 3d mouse drag #- self.mpl_canvas._tkcanvas.pack(side=tk.TOP, fill=tk.BOTH, expand=True)
def __init__(self, X, Y, Z, data, n, parent): self.fig = Figure() self.axes = self.fig.add_subplot(121) g = data data = data[:, :, int(np.fix(n * (len(Z) - 1) / np.max(Z)))] self.axes.imshow(data, cmap=plt.cm.jet, interpolation='nearest', origin='lower', extent=[np.min(X), np.max(X), np.min(Y), np.max(Y)], vmin=np.min(g), vmax=np.max(g)) self.axes2 = self.fig.add_subplot(122, projection='3d') FigureCanvas.__init__(self, self.fig) Axes3D.mouse_init(self.axes2) cset = self.axes2.contourf(X, Y, data, min(data.shape), zdir='z', offset=n, cmap=plt.cm.jet, vmin=np.min(g), vmax=np.max(g)) self.axes2.set_zlim((np.max(Z), np.min(Z))) self.fig.colorbar(cset) self.setParent(parent) FigureCanvas.setSizePolicy(self, QSizePolicy.Expanding, QSizePolicy.Expanding) FigureCanvas.updateGeometry(self)
def start_plot(self, n, l, m, X, Y, Z): self.fig.suptitle('Electron cloud Distribution of {}'.format( chooser(n, l, m)[1])) Axes3D.mouse_init(self.axes) x = np.linspace(-X, X, 100) y = np.linspace(-Y, Y, 100) z = np.linspace(-Z, Z, 100) ans_x, ans_y, ans_z, ans_x2, ans_y2, ans_z2 = [], [], [], [], [], [] for i in x: for j in y: for k in z: if 0.09 < chooser(n, l, m, i, j, k)[0] < 0.11: ans_x.append(i) ans_y.append(j) ans_z.append(k) if -0.11 < chooser(n, l, m, i, j, k)[0] < -0.09: ans_x2.append(i) ans_y2.append(j) ans_z2.append(k) self.axes.scatter(ans_x, ans_y, ans_z, c='b', alpha=0.3) self.axes.scatter(ans_x2, ans_y2, ans_z2, c='r', alpha=0.3) # self.axes.legend(loc=0) self.axes.grid(True) self.draw()
def create_graphic(result, dic, new): """ Create a 2D or 3D graphic depending on the number of selected variables in the dictionary or if result contains 'Performance' outcome (performances of SVM classifier) or 'Actions' outcome (containing tweet, sentiment and characteristic vector) :param result: list of element to be used in the creation of the graphic :param dic: dictionary containing all the IntVar of every variable selectable and the number of selected variable. Used to create the graphic :return: """ labels, vectors, graph_values = list(), list(), list() for element in result: labels.append(element[1][0]) vectors.append(element[1][1][0]) for index, key in enumerate(dic): if key is not "count": if dic[key].get(): graph_values.append([t[index] for t in vectors]) if dic["count"] == 2: ax = self.fig.add_subplot(111) dic_count = dict() for index, label in enumerate(labels): if label == "Negative": color = "red" elif label == "Positive": color = "green" else: color = "blue" try: dic_count[str(graph_values[0][index]) + str(graph_values[1][index])] += 1 except: dic_count[str(graph_values[0][index]) + str(graph_values[1][index])] = 1 ax.scatter(graph_values[0][index], graph_values[1][index], s=min(dic_count[str(graph_values[0][index]) + str(graph_values[1][index])] * 50, 2000), c=color, alpha=0.25) else: ax = self.fig.add_subplot(111, projection="3d") dic_count = dict() for index, label in enumerate(labels): if label == "Negative": color = "red" elif label == "Positive": color = "green" else: color = "blue" try: dic_count[str(graph_values[0][index]) + str(graph_values[1][index]) + str( graph_values[2][index])] += 1 except: dic_count[str(graph_values[0][index]) + str(graph_values[1][index]) + str( graph_values[2][index])] = 1 ax.scatter(graph_values[0][index], graph_values[1][index], graph_values[2][index], s=min(dic_count[str(graph_values[0][index]) + str(graph_values[1][index]) + str( graph_values[2][index])] * 50, 2000), c=color, alpha=0.25) ax.set_xlabel("X") ax.set_ylabel("Y") graph = FigureCanvasTkAgg(self.fig, self.graphic_frame[display.index("current") - 4]) if not new: self.canvas[display.index("current") - 4].grid_forget() self.canvas[display.index("current") - 4] = graph.get_tk_widget() self.canvas[display.index("current") - 4].grid() else: self.canvas.append(graph.get_tk_widget()) self.canvas[-1].grid() if dic["count"] == 3: Axes3D.mouse_init(ax)
worker = ComputeField(0, options) worker.signals.result.connect(self.on_calc_done) self.pool.start(worker) def on_calc_done(self, task): self.canvas1.draw() self.progressBar.setValue(100) self.btnField.setEnabled(True) if __name__ == '__main__': fig = Figure() ax = fig.add_subplot(111, projection='3d') #fig.tight_layout() Axes3D.mouse_init(ax) fig1 = Figure() ax1 = fig1.add_subplot(111) #fig1.tight_layout() app = QtGui.QApplication(sys.argv) app.setStyle(QtGui.QStyleFactory.create('Fusion')) main = Main() main.addmpl(fig) main.addfield(fig1) main.show() sys.exit(app.exec_()) # In Qt 5.2, we can do # view->setSizeAdjustPolicy(QAbstractScrollArea::AdjustToContentsOnFirstShow);
def __init__(self, data_file, data_type = 2, color_map = 'jet', plot_label = "", time_zone = 0, plot_max_freq = 30.0, run_quietly = False, save_file = '', parent = None): self.data_type = data_type self.data_file = VOAOutFile(data_file, \ time_zone=time_zone, \ data_type=self.data_type) self.image_defs = self.IMG_TYPE_DICT[self.data_type] #color_map = eval('P.cm.' + color_map) num_grp = self.data_file.get_number_of_groups() if num_grp < 2: md = Gtk.MessageDialog(parent, \ Gtk.DialogFlags.MODAL,\ Gtk.MessageType.ERROR, \ Gtk.ButtonsType.CANCEL, \ "There must be 2 groups or more") md.run() md.destroy() return plot_groups = list(range(0, num_grp)) self.subplots = [] number_of_subplots = len(plot_groups) matplotlib.rcParams['axes.edgecolor'] = 'gray' matplotlib.rcParams['axes.facecolor'] = 'white' matplotlib.rcParams['axes.grid'] = True matplotlib.rcParams['figure.facecolor'] = 'white' matplotlib.rcParams['legend.fancybox'] = True matplotlib.rcParams['legend.shadow'] = True matplotlib.rcParams['figure.subplot.hspace'] = 0.45 matplotlib.rcParams['figure.subplot.wspace'] = 0.35 matplotlib.rcParams['figure.subplot.right'] = 0.85 colorbar_fontsize = 12 self.main_title_fontsize = 24 matplotlib.rcParams['legend.fontsize'] = 12 matplotlib.rcParams['axes.labelsize'] = 12 matplotlib.rcParams['axes.titlesize'] = 10 matplotlib.rcParams['xtick.labelsize'] = 10 matplotlib.rcParams['ytick.labelsize'] = 10 self.x_axes_ticks = np.arange(0, 25, 2) self.fig = Figure() ax = Axes3D(self.fig) X = np.arange(0, 25) Y = np.arange(0, len(plot_groups)) X, Y = np.meshgrid(X, Y) data_buffer = [] # hold the Z data sets for chan_grp in plot_groups: (group_name, group_info, fot, muf, hpf, image_buffer) = \ self.data_file.get_group_data(chan_grp) # Copy the element at [0] to the tail of the array #to 'wrap-around' the values at 24hrs. np.resize(muf, len(muf)+1) muf[-1] = muf[0] data_buffer.append(muf) Z = np.vstack((tuple(data_buffer))) # set up the titles and labels ax.set_xticks(np.arange(0, 25, 2)) if (plot_max_freq==self.AUTOSCALE) : z_max = math.ceil(max(muf) / 5.0) * 5.0 z_max = min(plot_max_freq, 30.0) z_max = max(plot_max_freq, 5.0) else : z_max = math.ceil(plot_max_freq / 5.0) * 5.0 z_ticks = [2, 5] for z_tick_value in np.arange(10, z_max+1, 5): z_ticks.append(z_tick_value) #ax.set_yticks(z_ticks) #label axes tz_sign = '+' if (time_zone >= 0) else '' self.x_label = ax.set_xlabel('Time (UTC%s%s)' % (tz_sign, time_zone)) self.y_label = ax.set_ylabel('Group') self.z_label = ax.set_zlabel('Frequency (MHz)') #do the plot ax.plot_surface(X, Y, Z, rstride=1, cstride=1, cmap=color_map) canvas = FigureCanvasGTK3Agg(self.fig) canvas.show() Axes3D.mouse_init(ax) VOAPlotWindow('pythonProp - ' + self.image_defs['title'], \ canvas, \ parent) return
def plot_beam_xy(self, write_files=False, return_values=False, threeD=False): """ Plot beam center coordinates and a histogram of distances from the median of beam center coordinates to each set of coordinates. Superpose a predicted mis-indexing shift by L +/- 1 (calculated for each axis). """ # Calculate beam center coordinates and distances beamX = list(zip(*self.info.stats['beamX']['lst']))[2] beamY = list(zip(*self.info.stats['beamY']['lst']))[2] beamZ = list(zip(*self.info.stats['distance']['lst']))[2] beamXY = list(zip(beamX, beamY)) beam_dist = [ math.hypot(i[0] - np.median(beamX), i[1] - np.median(beamY)) for i in beamXY ] beam_dist_std = np.std(beam_dist) beamXYdist = list(zip(beamX, beamY, beam_dist)) # Separate out outliers outliers = [i for i in beamXYdist if i[2] > 2 * beam_dist_std] clean = [i for i in beamXYdist if i[2] <= 2 * beam_dist_std] cbeamX = [i[0] for i in clean] cbeamY = [j[1] for j in clean] obeamX = [i[0] for i in outliers] obeamY = [j[1] for j in outliers] wavelength = self.info.stats['wavelength']['median'] det_distance = self.info.stats['distance']['median'] a = np.median([i[0] for i in self.info.cluster_iterable]) b = np.median([i[1] for i in self.info.cluster_iterable]) c = np.median([i[2] for i in self.info.cluster_iterable]) # Calculate predicted L +/- 1 misindexing distance for each cell edge aD = det_distance * math.tan(2 * math.asin(wavelength / (2 * a))) bD = det_distance * math.tan(2 * math.asin(wavelength / (2 * b))) cD = det_distance * math.tan(2 * math.asin(wavelength / (2 * c))) # Plot figure if threeD: self.figure.set_size_inches(w=8, h=8) ax1 = self.figure.add_subplot(111, projection='3d') Axes3D.mouse_init(ax1) else: self.figure.set_size_inches(w=9, h=13) gsp = gridspec.GridSpec(2, 1, height_ratios=[3, 1]) ax1 = self.figure.add_subplot(gsp[0, :], aspect='equal') # Calculate axis limits of beam center scatter plot ax1_delta = np.ceil(np.max(beam_dist)) xmax = round(np.median(beamX) + ax1_delta) xmin = round(np.median(beamX) - ax1_delta) ymax = round(np.median(beamY) + ax1_delta) ymin = round(np.median(beamY) - ax1_delta) zmax = round(np.ceil(self.info.stats['distance']['max'])) zmin = round(np.floor(self.info.stats['distance']['min'])) ax1.set_xlim(xmin, xmax) ax1.set_ylim(ymin, ymax) if threeD: ax1.set_zlim(zmin, zmax) # Plot beam center scatter plot if threeD: ax1.scatter(beamX, beamY, beamZ, alpha=1, s=20, c='grey', lw=1) ax1.plot([self.info.stats['beamX']['median']], [self.info.stats['beamY']['median']], [self.info.stats['distance']['median']], markersize=8, marker='o', c='yellow', lw=2) else: ax1.scatter(cbeamX, cbeamY, alpha=1, s=20, c='grey', lw=1) ax1.scatter(obeamX, obeamY, alpha=1, s=20, c='red', lw=1) ax1.plot(np.median(beamX), np.median(beamY), markersize=8, marker='o', c='yellow', lw=2) # Plot projected mis-indexing limits for all three axes from matplotlib.patches import Circle circle_a = Circle((np.median(beamX), np.median(beamY)), radius=aD, color='r', fill=False, clip_on=True) circle_b = Circle((np.median(beamX), np.median(beamY)), radius=bD, color='g', fill=False, clip_on=True) circle_c = Circle((np.median(beamX), np.median(beamY)), radius=cD, color='b', fill=False, clip_on=True) ax1.add_patch(circle_a) ax1.add_patch(circle_b) ax1.add_patch(circle_c) # Set labels ax1.set_xlabel('BeamX (mm)', fontsize=15) ax1.set_ylabel('BeamY (mm)', fontsize=15) if threeD: ax1.set_zlabel('Distance (mm)', fontsize=15) ax1.set_title('Beam XYZ Coordinates') else: ax1.set_title('Beam XY Coordinates') if not threeD: # Plot histogram of distances to each beam center from median ax2 = self.figure.add_subplot(gsp[1, :]) ax2_n, ax2_bins, ax2_patches = ax2.hist(beam_dist, 20, facecolor='b', alpha=0.75, histtype='stepfilled') ax2_height = (np.max(ax2_n) + 9) // 10 * 10 ax2.axis([0, np.max(beam_dist), 0, ax2_height]) ax2.set_xlabel('Distance from median (mm)', fontsize=15) ax2.set_ylabel('No. of images', fontsize=15) self.draw(tight_layout=False)
else: return R5g(x, y, z) * gx4y4(x, y, z), '$5g_{x^4+y^4}$' X = 5 Y = 5 Z = 5 n = 2 l = 1 m = 0 #fig = plt.figure(figsize=(5, 5), dpi=100) fig = plt.figure() axes = fig.add_subplot(111, projection='3d') fig.suptitle('{}'.format(chooser(n, l, m)[1])) Axes3D.mouse_init(axes) x = np.linspace(-X, X, 20) y = np.linspace(-Y, Y, 20) z = np.linspace(-Z, Z, 20) ans_x, ans_y, ans_z, ans_x2, ans_y2, ans_z2 = [], [], [], [], [], [] for i in x: for j in y: for k in z: dst = chooser(n, l, m, i, j, k)[0]**2 if 0.001 < dst: dst = dst * 3 ans_x.append(i) ans_y.append(j) ans_z.append(k) dsta = dst if dst > 1:
def __init__(self, data, parent): lat, lon, depth, rms = self.extract(data) # lat = np.zeros((len(data),1)) # lon = np.zeros((len(data),1)) # depth = np.zeros((len(data),1)) # # for i in range(len(data)): # lat[i] = data[i][1] # lon[i] = data[i][2] # depth[i] = data[i][3] self.fig = Figure() gs = GridSpec(1, 7) self.axes = self.fig.add_subplot(gs[0, 0:2], aspect='equal') self.axes.set_title('Location of Event') self.axes.set_ylabel('X') self.axes.set_xlabel('Y') self.axes.scatter(lat, lon, color='red') self.axes.grid() # g = data # data = data[:,:,int(np.fix(n*(len(Z)-1)/np.max(Z)))] #------------------------ # m = Basemap(width=((lon.max()-lon.min())*111194.9266),height=((lat.max()-lat.min())*111194.9266),projection='aeqd', lat_0=lat.mean(), lon_0=lon.mean(), ax=self.axes) # fill background. # m.drawmapboundary(fill_color='aqua') # draw coasts and fill continents. # m.drawcoastlines(linewidth=0.5) # m.fillcontinents(color='coral', lake_color='aqua') # draw parallels. # parallels = np.arange(-90, 90, np.ceil((lat.max()-lat.min())/10)) # parallels = np.arange(lat.min(), lat.max(), np.round((lat.max() - lat.min()) * 0.1, 5)) # m.drawparallels(parallels, labels=[1, 0, 0, 0], fontsize=5) # draw meridians # meridians = np.arange(0, 360, np.ceil((lon.max()-lon.min())/10)) # meridians = np.arange(lon.min(), lon.max(), np.round((lon.max() - lon.min()) * 0.1, 5)) # m.drawmeridians(meridians, labels=[0, 0, 0, 1], fontsize=5) # draw a black dot at the center. # x,y = m(lon,lat) # m.plot(x, y, 'ro') #------------------------ self.axes3 = self.fig.add_subplot(gs[0, -1]) self.axes3.set_title('RMS Error (Hist)') self.axes3.set_ylabel('N Event') self.axes3.set_xlabel('RMS') self.axes3.hist(rms, bins='auto', color='blue') self.axes2 = self.fig.add_subplot(gs[0, 3:5], projection='3d') self.axes2.set_title('Location of Event') self.axes2.set_ylabel('X (km)') self.axes2.set_xlabel('Y (km)') self.axes2.set_zlabel('Depth (km)') # # FigureCanvas.__init__(self, self.fig) Axes3D.mouse_init(self.axes2) self.axes2.scatter(lat, lon, depth, color='red') # # self.axes2.set_zlim((np.max(depth), np.min(depth))) self.setParent(parent) FigureCanvas.setSizePolicy(self, QSizePolicy.Expanding, QSizePolicy.Expanding) FigureCanvas.updateGeometry(self)
self.pool.start(worker) def on_calc_done(self,task): self.canvas1.draw() self.progressBar.setValue(100) self.btnField.setEnabled(True) if __name__ == '__main__': fig = Figure() ax = fig.add_subplot(111, projection='3d') #fig.tight_layout() Axes3D.mouse_init(ax) fig1 = Figure() ax1 = fig1.add_subplot(111) #fig1.tight_layout() app = QtGui.QApplication(sys.argv) app.setStyle(QtGui.QStyleFactory.create('Fusion')) main = Main() main.addmpl(fig) main.addfield(fig1) main.show() sys.exit(app.exec_()) # In Qt 5.2, we can do