def __get_two_pane_one_pane_spec(self): ''' :return: layout spec with two panes with 2 axes in the first pane and 1 in the other. ''' major_ratio = [self.majorSplitRatio.value(), 1] minor_ratio = [self.minorSplitRatio.value(), 1] if self.chartSplit.currentText() == 'Horizontal': gs = GridSpec(2, 2, width_ratios=major_ratio, height_ratios=minor_ratio, wspace=self.widthSpacing.value(), hspace=self.heightSpacing.value()) spec_1 = gs.new_subplotspec((0, 0), 1, 1) spec_2 = gs.new_subplotspec((1, 0), 1, 1) spec_3 = gs.new_subplotspec((0, 1), 2, 1) else: gs = GridSpec(2, 2, width_ratios=minor_ratio, height_ratios=major_ratio, wspace=self.widthSpacing.value(), hspace=self.heightSpacing.value()) spec_1 = gs.new_subplotspec((0, 0), 1, 1) spec_2 = gs.new_subplotspec((0, 1), 1, 1) spec_3 = gs.new_subplotspec((1, 0), 2, 1) return spec_1, spec_2, spec_3
def create_canvas(self): # pragma: no cover self.fig = Figure() canvas = FigureCanvas(self.fig) self.ui.mainLayout.addWidget(canvas) canvas.setFocusPolicy(QtCore.Qt.StrongFocus) # Add subplots gridspec = GridSpec(2, 4) self.map_ax = self.fig.add_subplot( gridspec.new_subplotspec((0, 0), rowspan=2, colspan=2) ) self.spectrum_ax = self.fig.add_subplot( gridspec.new_subplotspec((0, 2), rowspan=1, colspan=2) ) self.hist_ax = self.fig.add_subplot( gridspec.new_subplotspec((1, 2), rowspan=1, colspan=1) ) self.edge_ax = self.fig.add_subplot( gridspec.new_subplotspec((1, 3), rowspan=1, colspan=1) ) # Create the colorbar on the histogram axes self.cbar = plots.draw_histogram_colorbar(ax=self.hist_ax, cmap="viridis", norm=Normalize(0, 1)) self.cbar.ax.set_xlabel("Map Value") # Adjust the margins self.fig.tight_layout(pad=0) self.fig.canvas.draw_idle()
def __render_both(self): ''' renders two plots, one with the filtered and one without. ''' times = {'start': time.time()} if self.__left_axes is None: self.__width_ratio = self.__make_width_ratio() gs = GridSpec(1, 2, width_ratios=self.__make_width_ratio(adjusted=True), wspace=0.00) gs.tight_layout(self.__chart.canvas.figure) self.__left_axes = self.__chart.canvas.figure.add_subplot( gs.new_subplotspec((0, 0))) self.__add_grid(self.__left_axes) self.__right_axes = self.__chart.canvas.figure.add_subplot( gs.new_subplotspec((0, 1))) self.__add_grid(self.__right_axes) times['l_axes_init'] = time.time() self.__left_scatter = self.__render_scatter( self.__left_cache, self.__left_axes, self.__left_scatter, self.__ui.maxFilteredFreq.value(), self.left, 'l', times) self.__set_limits(self.__left_axes, self.__ui.minFreq, self.__ui.maxFilteredFreq, self.__ui.minTime, self.__ui.maxTime) times['l_limits'] = time.time() self.__right_scatter = self.__render_scatter( self.__right_cache, self.__right_axes, self.__right_scatter, self.__ui.maxUnfilteredFreq.value(), self.right, 'r', times) self.__right_axes.set_yticklabels([]) self.__right_axes.get_yaxis().set_tick_params(length=0) self.__set_limits(self.__right_axes, self.__ui.minFreq, self.__ui.maxUnfilteredFreq, self.__ui.minTime, self.__ui.maxTime) times['r_limits'] = time.time() return times
def get_stereo_two_rose(self): """ Resets the figure and returns a stereonet two rose diagrams axis. When the view in the main window is changed to this setting, this function is called and sets up a plot with a stereonet and two rose diagram axis. One axis is for azimuth, the other one for dip. """ self.fig.clf() self.fig.patch.set_facecolor(self.props["canvas_color"]) self.fig.set_dpi(self.props["pixel_density"]) gridspec = GridSpec(2, 4) sp_stereo = gridspec.new_subplotspec((0, 0), rowspan=2, colspan=2) sp_cbar = gridspec.new_subplotspec((1, 2), rowspan=1, colspan=1) sp_rose = gridspec.new_subplotspec((0, 3), rowspan=1, colspan=1) sp_drose = gridspec.new_subplotspec((1, 3), rowspan=1, colspan=1) ax_stereo = self.fig.add_subplot(sp_stereo, projection=self.get_projection()) ax_rose = self.fig.add_subplot(sp_rose, projection="northpolar") ax_drose = self.fig.add_subplot(sp_drose, projection="dippolar") ax_cbar = self.fig.add_subplot(sp_cbar) ax_cbar.axis("off") ax_cbar.set_aspect(8) return ax_stereo, ax_rose, ax_drose, ax_cbar
def create_canvas(self): # Add the canvas to the UI self.fig = Figure() canvas = FigureCanvas(self.fig) self.ui.mainLayout.addWidget(canvas) # Add subplots gridspec = GridSpec(2, 4) self.img_ax = self.fig.add_subplot( gridspec.new_subplotspec((0, 0), rowspan=2, colspan=2) ) self.spectrum_ax = self.fig.add_subplot( gridspec.new_subplotspec((0, 2), rowspan=1, colspan=2) ) self.hist_ax = self.fig.add_subplot( gridspec.new_subplotspec((1, 2), rowspan=1, colspan=1) ) self.edge_ax = self.fig.add_subplot( gridspec.new_subplotspec((1, 3), rowspan=1, colspan=1) ) # Create the colorbar on the histogram axes self.cbar = plots.draw_histogram_colorbar(ax=self.hist_ax, cmap="viridis", norm=Normalize(0, 1)) self.cbar.ax.set_xlabel("Intensity") # Adjust the margins self.fig.tight_layout(pad=0) self.fig.canvas.draw_idle()
def get_stereo_rose(self): """ Resets the figure and returns a stereonet and rose diagram axis. When the view in the main window is changed to stereonet and rose diagram, the figure is reset. The current settings are applied and two subplots for the stereonet and rose diagram are created. The axis of the stereonet and rose diagram are returned. This method is called by the MainWindow "redraw_plot"-method. """ self.fig.clf() self.fig.patch.set_facecolor(self.props["canvas_color"]) self.fig.set_dpi(self.props["pixel_density"]) gridspec = GridSpec(2, 5) sp_stereo = gridspec.new_subplotspec((0, 0), rowspan=2, colspan=2) sp_cbar = gridspec.new_subplotspec((1, 2), rowspan=1, colspan=1) sp_rose = gridspec.new_subplotspec((0, 3), rowspan=2, colspan=2) ax_stereo = self.fig.add_subplot(sp_stereo, projection=self.get_projection()) ax_rose = self.fig.add_subplot(sp_rose, projection="northpolar") ax_cbar = self.fig.add_subplot(sp_cbar) ax_cbar.axis("off") ax_cbar.set_aspect(8) return ax_stereo, ax_rose, ax_cbar
def get_stereo_rose(self): """ Resets the figure and returns a stereonet and rose diagram axis. When the view in the main window is changed to stereonet and rose diagram, the figure is reset. The current settings are applied and two subplots for the stereonet and rose diagram are created. The axis of the stereonet and rose diagram are returned. This method is called by the MainWindow "redraw_plot"-method. """ self.fig.clf() self.fig.patch.set_facecolor(self.props["canvas_color"]) self.fig.set_dpi(self.props["pixel_density"]) gridspec = GridSpec(2, 5) sp_stereo = gridspec.new_subplotspec((0, 0), rowspan=2, colspan=2) sp_cbar = gridspec.new_subplotspec((1, 2), rowspan=1, colspan=1) sp_rose = gridspec.new_subplotspec((0, 3), rowspan=2, colspan=2) ax_stereo = self.fig.add_subplot(sp_stereo, projection=self.get_projection()) ax_rose = self.fig.add_subplot(sp_rose, projection="northpolar") ax_cbar = self.fig.add_subplot(sp_cbar) ax_cbar.axis("off") ax_cbar.set_aspect(8) return ax_stereo, ax_rose, ax_cbar
def get_stereo_two_rose(self): """ Resets the figure and returns a stereonet two rose diagrams axis. When the view in the main window is changed to this setting, this function is called and sets up a plot with a stereonet and two rose diagram axis. One axis is for azimuth, the other one for dip. """ self.fig.clf() self.fig.patch.set_facecolor(self.props["canvas_color"]) self.fig.set_dpi(self.props["pixel_density"]) gridspec = GridSpec(2, 4) sp_stereo = gridspec.new_subplotspec((0, 0), rowspan=2, colspan=2) sp_cbar = gridspec.new_subplotspec((1, 2), rowspan=1, colspan=1) sp_rose = gridspec.new_subplotspec((0, 3), rowspan=1, colspan=1) sp_drose = gridspec.new_subplotspec((1, 3), rowspan=1, colspan=1) ax_stereo = self.fig.add_subplot(sp_stereo, projection=self.get_projection()) ax_rose = self.fig.add_subplot(sp_rose, projection="northpolar") ax_drose = self.fig.add_subplot(sp_drose, projection="dippolar") ax_cbar = self.fig.add_subplot(sp_cbar) ax_cbar.axis("off") ax_cbar.set_aspect(8) return ax_stereo, ax_rose, ax_drose, ax_cbar
def __init__(self, main_window, settings, data, add_layer_dataset, add_feature, redraw_main): """ Initializes the RotationDialog class. Requires the main_window object, the settings object (PlotSettings class) and the data rows to initialize. All the necessary widgets are loaded from the Glade file. A matplotlib figure is set up and added to the scrolledwindow. Two axes are set up that show the original and rotated data. """ self.builder = Gtk.Builder() self.builder.set_translation_domain(i18n().get_ts_domain()) script_dir = os.path.dirname(__file__) rel_path = "gui_layout.glade" abs_path = os.path.join(script_dir, rel_path) self.builder.add_objects_from_file(abs_path, ("dialog_rotation", "adjustment_rotation_dipdir", "adjustment_rotation_dip", "adjustment_rotation_angle")) self.dialog = self.builder.get_object("dialog_rotation") self.dialog.set_transient_for(main_window) self.settings = settings self.data = data self.trans = self.settings.get_transform() self.add_layer_dataset = add_layer_dataset self.add_feature = add_feature self.redraw_main = redraw_main self.adjustment_rotation_dipdir = self.builder.get_object("adjustment_rotation_dipdir") self.adjustment_rotation_dip = self.builder.get_object("adjustment_rotation_dip") self.adjustment_rotation_angle = self.builder.get_object("adjustment_rotation_angle") self.spinbutton_rotation_dipdir = self.builder.get_object("spinbutton_rotation_dipdir") self.spinbutton_rotation_dip = self.builder.get_object("spinbutton_rotation_dip") self.spinbutton_rotation_angle = self.builder.get_object("spinbutton_rotation_angle") self.scrolledwindow_rotate = self.builder.get_object("scrolledwindow_rotate") self.fig = Figure(dpi=self.settings.get_pixel_density()) self.canvas = FigureCanvas(self.fig) self.scrolledwindow_rotate.add_with_viewport(self.canvas) gridspec = GridSpec(1, 2) original_sp = gridspec.new_subplotspec((0, 0), rowspan=1, colspan=1) rotated_sp = gridspec.new_subplotspec((0, 1), rowspan=1, colspan=1) self.original_ax = self.fig.add_subplot(original_sp, projection=self.settings.get_projection()) self.rotated_ax = self.fig.add_subplot(rotated_sp, projection=self.settings.get_projection()) self.canvas.draw() self.redraw_plot() self.dialog.show_all() self.builder.connect_signals(self) if sys.platform == "win32": translate_gui(self.builder)
def __init__(self, scale, imshape, interval=1): self.fig = plt.figure(dpi=100) self.axes = {} self.artists = [] gridspec = GridSpec(2, 2) self.axes['raw'] = gridspec.new_subplotspec((0, 0), rowspan=2) self.axes['draw'] = gridspec.new_subplotspec((0, 1)) self.axes['match'] = gridspec.new_subplotspec((1, 1)) for k, sp in self.axes.items(): self.axes[k] = self.fig.add_subplot(sp) self.axes['raw'].set_title('raw') self.axes['raw'].set_xticklabels([]) self.axes['raw'].set_yticklabels([]) self.axes['match'].grid(which='both') self.lines = {} self.lines['template'] = self.axes['match'].plot((), (), marker='x', color='g')[0] self.lines['query'] = self.axes['match'].plot((), (), marker='o', color='b')[0] self.lines['draw'] = self.axes['draw'].plot((), (), color='b', linewidth=5)[0] self.axes['match'].set_ylim(-scale // 2 - 10, scale // 2 + 10) self.axes['match'].set_xlim(-scale // 2 - 10, scale // 2 + 10) self.axes['draw'].set_ylim(imshape[0], 0) self.axes['draw'].set_xlim(imshape[1], 0) self.axes['draw'].xaxis.tick_top() self.axes['draw'].yaxis.tick_right() self.imdisp = self.axes['raw'].imshow(np.zeros(imshape, dtype=np.uint8)) self.fig.tight_layout() self.bg_cache = { ax: self.fig.canvas.copy_from_bbox(ax.bbox) for ax in self.fig.axes } self.draw_state = 0 self.drawcount = 0 self.fig.canvas.mpl_connect('button_press_event', self.onclick) self.fig.canvas.mpl_connect('key_press_event', self.onkey) self.timer = self.fig.canvas.new_timer(interval=interval) self.timer.add_callback(self._update) self.queuelen = 0
def __get_two_pane_spec(self): ''' :return: layout spec with two panes containing an axes in each. ''' if self.chartSplit.currentText() == 'Horizontal': gs = GridSpec(1, 2, width_ratios=[self.majorSplitRatio.value(), 1], wspace=self.widthSpacing.value(), hspace=self.heightSpacing.value()) spec_1 = gs.new_subplotspec((0, 0), 1, 1) spec_2 = gs.new_subplotspec((0, 1), 1, 1) else: gs = GridSpec(2, 1, height_ratios=[self.majorSplitRatio.value(), 1], wspace=self.widthSpacing.value(), hspace=self.heightSpacing.value()) spec_1 = gs.new_subplotspec((0, 0), 1, 1) spec_2 = gs.new_subplotspec((1, 0), 1, 1) return spec_1, spec_2
def plot_step_detection(): """ PLOTTING SETUP """ fig = plt.figure() gridspec = GridSpec(2, 1, height_ratios=[1, 1]) ax1 = fig.add_subplot(gridspec.new_subplotspec((0, 0))) ax2 = fig.add_subplot(gridspec.new_subplotspec((1, 0))) # Set up the 2D floor ax1.set_ylim(0, 2) """ 2D FLOOR VIEW """ # ax1.set_axis_off() # ax1.set_xticklabels([]) # ax1.set_yticklabels([]) ax1.scatter(cop.x, cop.y, c=cop.magnitude, cmap='Greys', s=5) ax1.scatter(rights.x, rights.y, c='red', marker='o') ax1.scatter(lefts.x, lefts.y, c='blue', marker='o') ax1.plot(*zip(start.to_array(), end.to_array()), c='r', linestyle=':') """ COP PARAMS SERIES """ # ax2.set_axis_off() ax2.set_yticklabels([]) ax2.set_xlim(cop_speed.time[0].values, cop_speed.time[-1].values) cop_speed.plot(ax=ax2) (cop_speed_roc / 10).plot(ax=ax2) for support in steps.dir: ax2.axvline(support.time.values, c=('r' if support.item() == 'right' else 'b'), linestyle='--') for strike in floor.heelstrikes.dir: ax2.axvline(strike.time.values, c='gray', linestyle=':') plt.setp(ax2.xaxis.get_majorticklabels(), rotation='horizontal', ha='center', size=6)
def gridplot (grid, loc, rowspan=1, colspan=1): ''' Returns a matplotlib.gridspec.SubplotSpec for a subplot. The resulting object can then be added to a matplotlib.figure using the add_subplot() method. ''' gridspec = GridSpec (grid[0], grid[1]) subplotspec = gridspec.new_subplotspec(loc, rowspan, colspan) return subplotspec
def __init__(self, chart, measurement_model, display_model, preferences): self.__chart = chart self.__measurement_model = measurement_model self.name = f"multi" self.__data = MarkerData() gs = GridSpec(2, 3, width_ratios=[1, 1, 0.75]) self.__magnitude = AnimatedSingleLineMagnitudeModel(self.__chart, self.__measurement_model, display_model, self.__data, subplot_spec=gs.new_subplotspec((0, 0), 1, 2)) self.__sonagram = ContourModel(self.__chart, self.__measurement_model, display_model, preferences, subplot_spec=gs.new_subplotspec((1, 0), 1, 2), redraw_on_display=False, show_crosshairs=True) self.__polar = PolarModel(self.__chart, self.__measurement_model, display_model, self.__data, subplotSpec=gs.new_subplotspec((1, 2), 1, 1)) self.__table_axes = self.__chart.canvas.figure.add_subplot(gs.new_subplotspec((0, 2), 1, 1)) self.__table = None self.__ani = None self.__stopping = False self.__mouse_reactor = MouseReactor(0.10, self.propagateCoords)
def create_plot_collage(iteration_step): # define file paths for 2d and 1d data, then load them in path_to_2D_data = f'../fargo2d1d/{SIMULATION_DIR}/{SIMULATION_ID}/out/gasdens{iteration_step}.dat' path_to_1D_data = f'../fargo2d1d/{SIMULATION_DIR}/{SIMULATION_ID}/out/gasdens.ascii_rad.{iteration_step}.dat' if not os.path.exists(path_to_1D_data): return #raise FileNotFoundError(f'could not find file {path_to_1D_data}') if not os.path.exists(path_to_2D_data): return #raise FileNotFoundError(f'could not find file {path_to_2D_data}') print(f'plotting data for file {iteration_step}') fig = plt.figure(figsize=(15, 10)) gs = GridSpec(2, 3, figure=fig) # plot 2d data in rectangular grid ax = fig.add_subplot(gs.new_subplotspec((0, 0), colspan=3)) create_cartesian_2D_plot(ax, path_to_2D_data, iteration_step) # plot 1d data ax = plt.subplot(gs.new_subplotspec((1, 0), colspan=1)) create_1D_plot(ax, path_to_1D_data) # get info ax = plt.subplot(gs.new_subplotspec((1, 1), colspan=1)) create_info_box(ax, iteration_step) # plot 2d data in polar coords ax = plt.subplot(gs.new_subplotspec((1, 2), colspan=1), projection='polar') create_polar_2D_plot(ax, path_to_2D_data) # make sure sorting is done right if iteration_step < 10: iteration_step = f'0{iteration_step}' # save and reset figure plt.savefig(f'{FIGURES_DIR}all_collages/collage_{iteration_step}.png') if iteration_step == get_total_nr_of_steps(SIMULATION_DIR, SIMULATION_ID) - 1: plt.savefig(f'{FIGURES_DIR}collage_for_outfile_{iteration_step}.png') plt.clf() plt.close()
def __init__(self, canvas, num): backend_gtkagg.FigureManagerGTKAgg.__init__(self, canvas, num) self.window.maximize() self.vbox.remove(self.canvas) self.menu = Menu(self) self.vbox.pack_start(self.menu, False, True) self.vbox1 = gtk.VBox() self.vbox1.pack_start(self.canvas, True, True) self.vbox1.show() self.vpane = gtk.HBox() self.vbox.pack_start(self.vpane, True, True) self.vpane.pack_start(self.vbox1, True, True) self.vpane.show() self.sidebar = Sidebar(self) self.sidebar.widget.show() self.vpane.pack_end(self.sidebar.widget, False, True) grid = GridSpec(4, 1) spec = grid.new_subplotspec((0, 0), rowspan=3) self.ax = self.canvas.figure.add_subplot(spec) spec = grid.new_subplotspec((3, 0), rowspan=1) self.ax2 = self.canvas.figure.add_subplot(spec, sharex=self.ax) self.ax2.grid(True) self.text = self.ax.text( 0.90, 0.90, r'', horizontalalignment='center', verticalalignment='center', transform=self.ax.transAxes, fontsize=20, ) self.reset_margins()
def __init__(self,scale,imshape,interval=1): self.fig = plt.figure(dpi=100) self.axes = {} self.artists = [] gridspec = GridSpec(2,2) self.axes['raw'] = gridspec.new_subplotspec((0, 0),rowspan=2) self.axes['draw'] = gridspec.new_subplotspec((0, 1)) self.axes['match'] = gridspec.new_subplotspec((1, 1)) for k,sp in self.axes.items(): self.axes[k] = self.fig.add_subplot(sp) self.axes['raw'].set_title('raw') self.axes['raw'].set_xticklabels([]) self.axes['raw'].set_yticklabels([]) self.axes['match'].grid(which='both') self.lines = {} self.lines['template'] = self.axes['match'].plot((),(),marker='x',color='g')[0] self.lines['query'] = self.axes['match'].plot((),(),marker='o',color='b')[0] self.lines['draw'] = self.axes['draw'].plot((),(),color='b',linewidth=5)[0] self.axes['match'].set_ylim(-scale//2-10,scale//2+10) self.axes['match'].set_xlim(-scale//2-10,scale//2+10) self.axes['draw'].set_ylim(imshape[0],0) self.axes['draw'].set_xlim(imshape[1],0) self.axes['draw'].xaxis.tick_top() self.axes['draw'].yaxis.tick_right() self.imdisp = self.axes['raw'].imshow(np.zeros(imshape,dtype=np.uint8)) self.fig.tight_layout() self.bg_cache = {ax:self.fig.canvas.copy_from_bbox(ax.bbox) for ax in self.fig.axes} self.draw_state = 0 self.drawcount = 0 self.fig.canvas.mpl_connect('button_press_event', self.onclick) self.fig.canvas.mpl_connect('key_press_event', self.onkey) self.timer = self.fig.canvas.new_timer(interval=interval) self.timer.add_callback(self._update) self.queuelen = 0
def get_stereonet(self): """ Resets the figure and returns the stereonet axis. When the view in the main window is changed to only stereoent. The figure is reset. Then the current settings are applied and one subplot for the stereonet is created. This method is called when the MainWindow "__init__"-method and the "redraw_plot"-method. """ self.fig.clf() self.fig.patch.set_facecolor(self.props["canvas_color"]) self.fig.set_dpi(self.props["pixel_density"]) gridspec = GridSpec(2, 3) sp_stereo = gridspec.new_subplotspec((0, 0), rowspan=2, colspan=2) sp_cbar = gridspec.new_subplotspec((1, 2), rowspan=1, colspan=1) ax_stereo = self.fig.add_subplot(sp_stereo, projection=self.get_projection()) ax_cbar = self.fig.add_subplot(sp_cbar) ax_cbar.axis("off") ax_cbar.set_aspect(8) return ax_stereo, ax_cbar
def get_pt_view(self): """ Resets the canvas and returns the 3 axis of the paleostress view. When the view in the main window is changed to paleostress the figure is reset. The current settings are applied and 3 subplots are created. The 3 axis of the subplots are returned. This method is called by the MainWindow "redraw_plot"-method when the view has been changed. """ self.fig.clf() self.fig.patch.set_facecolor(self.props["canvas_color"]) self.fig.set_dpi(self.props["pixel_density"]) gridspec = GridSpec(2, 5) sp_stereo = gridspec.new_subplotspec((0, 0), colspan=3, rowspan=2) sp_fluc = gridspec.new_subplotspec((0, 3), colspan=2) sp_mohr = gridspec.new_subplotspec((1, 3), colspan=2) ax_stereo = self.fig.add_subplot(sp_stereo, projection=self.get_projection()) ax_fluc = self.fig.add_subplot(sp_fluc, aspect="equal") ax_mohr = self.fig.add_subplot(sp_mohr, aspect="equal") return ax_stereo, ax_fluc, ax_mohr
def get_pt_view(self): """ Resets the canvas and returns the 3 axis of the paleostress view. When the view in the main window is changed to paleostress the figure is reset. The current settings are applied and 3 subplots are created. The 3 axis of the subplots are returned. This method is called by the MainWindow "redraw_plot"-method when the view has been changed. """ self.fig.clf() self.fig.patch.set_facecolor(self.props["canvas_color"]) self.fig.set_dpi(self.props["pixel_density"]) gridspec = GridSpec(2, 5) sp_stereo = gridspec.new_subplotspec((0, 0), colspan=3, rowspan=2) sp_fluc = gridspec.new_subplotspec((0, 3), colspan=2) sp_mohr = gridspec.new_subplotspec((1, 3), colspan=2) ax_stereo = self.fig.add_subplot(sp_stereo, projection=self.get_projection()) ax_fluc = self.fig.add_subplot(sp_fluc, aspect="equal") ax_mohr = self.fig.add_subplot(sp_mohr, aspect="equal") return ax_stereo, ax_fluc, ax_mohr
def get_stereonet(self): """ Resets the figure and returns the stereonet axis. When the view in the main window is changed to only stereoent. The figure is reset. Then the current settings are applied and one subplot for the stereonet is created. This method is called when the MainWindow "__init__"-method and the "redraw_plot"-method. """ self.fig.clf() self.fig.patch.set_facecolor(self.props["canvas_color"]) self.fig.set_dpi(self.props["pixel_density"]) gridspec = GridSpec(2, 3) sp_stereo = gridspec.new_subplotspec((0, 0), rowspan=2, colspan=2) sp_cbar = gridspec.new_subplotspec((1, 2), rowspan=1, colspan=1) ax_stereo = self.fig.add_subplot(sp_stereo, projection=self.get_projection()) ax_cbar = self.fig.add_subplot(sp_cbar) ax_cbar.axis("off") ax_cbar.set_aspect(8) return ax_stereo, ax_cbar
def consumme_window(window, loader): """ Consumme a Window object to create a matplotlib figure adjusted by the GridSpec """ fig = figure(window.name, figsize=(15, 10)) grid = GridSpec(window.rows, window.cols, figure=fig) for i, _ in enumerate(window.content): span = 0 for j, col in enumerate(window.content[i]): sub = fig.add_subplot( grid.new_subplotspec((i, j + span), colspan=int(window.span[i][j]))) span += int(window.span[i][j]) - 1 load_sub_plots(sub, loader, col, window.cfg)
def get_rose_diagram(self): """ Resets the figure and returns the rose diagram axis. When the view in the main window is changed to rose-diagram-only the figure is reset. The current settings are applied and one subplot for the rose diagram is created. The axis of the rose-diagram is returned. This method is called by the MainWindow "redraw_plot"-method. """ self.fig.clf() self.fig.patch.set_facecolor(self.props["canvas_color"]) self.fig.set_dpi(self.props["pixel_density"]) gridspec = GridSpec(1, 1) sp_rose = gridspec.new_subplotspec((0, 0)) ax_rose = self.fig.add_subplot(sp_rose, projection="northpolar") return ax_rose
def get_rose_diagram(self): """ Resets the figure and returns the rose diagram axis. When the view in the main window is changed to rose-diagram-only the figure is reset. The current settings are applied and one subplot for the rose diagram is created. The axis of the rose-diagram is returned. This method is called by the MainWindow "redraw_plot"-method. """ self.fig.clf() self.fig.patch.set_facecolor(self.props["canvas_color"]) self.fig.set_dpi(self.props["pixel_density"]) gridspec = GridSpec(1, 1) sp_rose = gridspec.new_subplotspec((0, 0)) ax_rose = self.fig.add_subplot(sp_rose, projection="northpolar") return ax_rose
def get_stereonet(self): """ Resets the figure and returns the stereonet axis. When the view in the main window is changed to only stereoent. The figure is reset. Then the current settings are applied and one subplot for the stereonet is created. This method is called when the MainWindow "__init__"-method and the "redraw_plot"-method. """ self.fig.clf() self.fig.patch.set_facecolor(self.canvas_color) self.fig.set_dpi(self.pixel_density) gridspec = GridSpec(1, 1) sp_stereo = gridspec.new_subplotspec((0, 0)) ax_stereo = self.fig.add_subplot(sp_stereo, projection=self.get_projection()) return ax_stereo
def plot_motion_similarity(): fig = plt.figure() cycle = cycles[1] cycle_cop = cop.sel(time=slice(*cycle.date_window)) cycle_cop_vel = floor.cop_vel.sel(time=slice(*cycle.date_window)) gridspec = GridSpec(1, 2, width_ratios=[2, 1]) ax1 = fig.add_subplot(gridspec.new_subplotspec((0, 0))) ax2 = fig.add_subplot(gridspec.new_subplotspec((0, 1))) """ LEFT PLOT """ ax1.plot(*zip(start.to_array(), end.to_array()), c='r', linestyle=':') ax1.set_xlim(cycle_cop.x.min().item(), cycle_cop.x.max().item()) ax1.quiver(cycle_cop.x, cycle_cop.y, cycle_cop_vel.x, cycle_cop_vel.y, angles='xy', units='dots', width=5, pivot='mid', cmap='cool') """ RIGHT PLOT """ ax2.axvline(0, c='r', linestyle=':') ax2.quiver(cycle.cop_mlap.med, cycle.cop_mlap.ant, cycle.cop_vel_mlap.med, cycle.cop_vel_mlap.ant, range(40), angles='xy', units='dots', width=5, pivot='mid', cmap='cool') ax2.set_xlim(-0.5, 0.5)
def initialize_subplots(self): gs = GridSpec(3, 4) # X componet self.subplots['xts'] = gs.new_subplotspec((0, 0), 1, 2) self.subplots['xke'] = gs.new_subplotspec((0, 2), 1, 1) self.subplots['xfas'] = gs.new_subplotspec((0, 3), 1, 1) # Y component self.subplots['yts'] = gs.new_subplotspec((1, 0), 1, 2) self.subplots['yke'] = gs.new_subplotspec((1, 2), 1, 1) self.subplots['yfas'] = gs.new_subplotspec((1, 3), 1, 1) # Z component self.subplots['zts'] = gs.new_subplotspec((1, 0), 1, 2) self.subplots['zke'] = gs.new_subplotspec((1, 2), 1, 1) self.subplots['zfas'] = gs.new_subplotspec((1, 3), 1, 1) for k, v in self.subplots.iteritems(): self.subplots[key] = self.add_subplot(val) return
def plot_lightcurve( lc1, time_bin=20, # Minutes base_model_flux=None, transit_datetimes=None, title=None, colors='rgb', offset_delta=0.): # Setup figure fig = Figure() FigureCanvas(fig) fig.set_size_inches(14, 7) fig.set_facecolor('white') grid_size = (9, 9) # Axis for light curve gs = GridSpec(*grid_size, hspace=0.1) offset = 0 # offset # Better time axis ticks half_hour = mdates.MinuteLocator(interval=30) h_fmt = mdates.DateFormatter('%H:%M:%S') for i, color in enumerate(colors): # Light curve plot spec1 = gs.new_subplotspec((i * 3, 0), colspan=7, rowspan=2) lc_ax = fig.add_subplot(spec1) lc_ax.set_xticks([]) lc_ax.set_ylim([0.93, 1.07]) # Residual spec2 = gs.new_subplotspec((i * 3 + 2, 0), colspan=7, rowspan=1) res_scatter_ax = fig.add_subplot(spec2) res_scatter_ax.set_ylim([-0.05, 0.05]) res_scatter_ax.set_yticks([-0.025, 0.025]) if i != 2: res_scatter_ax.set_xticks([]) else: res_scatter_ax.xaxis.set_major_locator(half_hour) res_scatter_ax.xaxis.set_major_formatter(h_fmt) # Residual histos spec = GridSpec(*grid_size).new_subplotspec((i * 3, 7), colspan=2, rowspan=3) res_ax = fig.add_subplot(spec) res_ax.set_xticks([]) res_ax.set_ylim([-.05, .05]) res_ax.set_yticks([-.025, 0, .025]) res_ax.yaxis.tick_right() res_ax.yaxis.set_major_formatter(PercentFormatter(xmax=1, decimals=1)) # Get the normalized flux for each channel flux_df = lc1.loc[lc1.color == color].copy() # Model flux if base_model_flux is None: flux_df['model'] = np.ones_like(flux_df.flux) else: flux_df['model'] = base_model_flux # Residual flux_df['residual'] = flux_df.flux - flux_df.model # Start plotting. # Plot target flux. flux_df.flux.plot( yerr=flux_df.flux_err, marker='o', ls='', alpha=0.15, color=color, ax=lc_ax, rot=0, # Don't rotate date labels legend=False, ) if time_bin is not None: # Time-binned binned_flux_df = flux_df.resample(f'{time_bin}T').apply({ 'flux': np.mean, 'flux_err': lambda x: np.sum(x**2) }) # Plot time-binned target flux. binned_flux_df.plot( yerr=binned_flux_df.flux_err, ax=lc_ax, rot=0, marker='o', ms=8, color=color, ls='', label=f'Time-binned - {time_bin}min', legend=False, ) # Plot model flux. flux_df.model.plot( ax=lc_ax, ls='-', color=color, alpha=0.5, lw=3, rot=0, # Don't rotate date labels label='Model fit', legend=True) # Residual scatter flux_df.residual.plot( ax=res_scatter_ax, color=color, ls='', marker='o', rot=0, # Don't rotate date labels alpha=0.5) # Residual histogram res_ax.hist(flux_df.residual, orientation='horizontal', color=color, alpha=0.5) res_ax.axhline(0, ls='--', color='k', alpha=0.25) res_ax.set_title(f'σ={flux_df.residual.std():.2%}', y=.82) # Add the offset offset += offset_delta if transit_datetimes is not None: midpoint, ingress, egress = transit_datetimes lc_ax.axvline(midpoint, ls='-.', c='g', alpha=0.5) lc_ax.axvline(ingress, ls='--', c='k', alpha=0.5) lc_ax.axvline(egress, ls='--', c='k', alpha=0.5) if title is not None: fig.suptitle(title, fontsize=18) return fig
def plot_spectral_levels(yvar, yname, color): #yvar either vs30 or GMPE site residual #cbar is True or False for coloring by vs30 fig = plt.figure(figsize=(18, 6)) fig.subplots_adjust(wspace=0) gs = GridSpec(1, 3) cmap = mpl.cm.viridis norm = mpl.colors.Normalize(vmin=min(sitevs30), vmax=max(sitevs30)) s_m = mpl.cm.ScalarMappable(cmap=cmap, norm=norm) s_m.set_array([]) #1-6Hz subplot ax1 = plt.subplot(gs.new_subplotspec((0, 0), colspan=1)) if color == True: plt.scatter(l, yvar, marker='o', s=60, c=s_m.to_rgba(sitevs30), edgecolors=s_m.to_rgba(sitevs30)) else: plt.scatter(l, yvar, marker='o', s=60, c='blue') for i in range(len(l)): #default 2,5 plt.annotate(site[i], xy=(l[i], yvar[i]), xytext=(2, 2), textcoords='offset points', fontsize=20) plt.ylabel(yname) rval, pval = pearsonr(l, siteterm) power = statsmodels.stats.power.tt_solve_power(effect_size=rval, nobs=len(l), alpha=0.05) label1 = 'Pearson R : ' + str(round(rval, 4)) label2 = 'power : ' + str(round(power, 4)) plt.annotate(label1, xy=(0.2, 0.16), xycoords='figure fraction', fontsize=16) plt.annotate(label2, xy=(0.2, 0.13), xycoords='figure fraction', fontsize=16) #6-14Hz subplot ax2 = plt.subplot(gs.new_subplotspec((0, 1), colspan=1), sharey=ax1) plt.setp(ax2.get_yticklabels(), visible=False) if color == True: plt.scatter(m, yvar, marker='o', s=60, c=s_m.to_rgba(sitevs30), edgecolors=s_m.to_rgba(sitevs30)) else: plt.scatter(m, yvar, marker='o', s=60, c='blue') for i in range(len(m)): #default 2,5 plt.annotate(site[i], xy=(m[i], yvar[i]), xytext=(2, 2), textcoords='offset points', fontsize=20) rval, pval = pearsonr(m, siteterm) power = statsmodels.stats.power.tt_solve_power(effect_size=rval, nobs=len(m), alpha=0.05) label1 = 'Pearson R : ' + str(round(rval, 4)) label2 = 'power : ' + str(round(power, 4)) plt.annotate(label1, xy=(0.5, 0.16), xycoords='figure fraction', fontsize=16) plt.annotate(label2, xy=(0.5, 0.13), xycoords='figure fraction', fontsize=16) #14-36Hz subplot ax3 = plt.subplot(gs.new_subplotspec((0, 2), colspan=1), sharey=ax1) plt.setp(ax3.get_yticklabels(), visible=False) if color == True: plt.scatter(h, yvar, marker='o', s=60, c=s_m.to_rgba(sitevs30), edgecolors=s_m.to_rgba(sitevs30)) else: plt.scatter(h, yvar, marker='o', s=60, c='blue') for i in range(len(h)): #default 2,5 plt.annotate(site[i], xy=(h[i], yvar[i]), xytext=(2, 2), textcoords='offset points', fontsize=20) rval, pval = pearsonr(h, siteterm) power = statsmodels.stats.power.tt_solve_power(effect_size=rval, nobs=len(h), alpha=0.05) label1 = 'Pearson R : ' + str(round(rval, 4)) label2 = 'power : ' + str(round(power, 4)) plt.annotate(label1, xy=(0.8, 0.16), xycoords='figure fraction', fontsize=16) plt.annotate(label2, xy=(0.8, 0.13), xycoords='figure fraction', fontsize=16) if color == True: ##add color bar to right cbar = plt.colorbar(s_m) cbar.set_label(ur"Vs30 (m/s)", fontsize=18) #"$azimuth$ (\u00b0)" cbar.ax.tick_params(labelsize=18) plt.show() plt.savefig(top_dir + 'tstar/site/' + 'spectral_amplitude_vs_' + yname + '.png')
def plot_lightcurve_combined( lc1, time_bin=20, # Minutes base_model_flux=None, transit_datetimes=None, title=None, colors='rgb', offset_delta=0.): # Setup figure fig = Figure() FigureCanvas(fig) fig.set_size_inches(14, 7) fig.set_facecolor('white') grid_size = (9, 9) # Axis for light curve gs = GridSpec(*grid_size, hspace=2) # Main plot spec1 = gs.new_subplotspec((0, 0), colspan=7, rowspan=7) lc_ax = fig.add_subplot(spec1) # Residual spec2 = gs.new_subplotspec((7, 0), colspan=7, rowspan=2) res_scatter_ax = fig.add_subplot(spec2) res_scatter_ax.set_ylim([-0.05, 0.05]) # Residual histos res_histo_axes = list() for i in range(3): spec = GridSpec(*grid_size).new_subplotspec((i * 3, 7), colspan=2, rowspan=3) res_ax = fig.add_subplot(spec) res_ax.set_xticks([]) res_ax.set_ylim([-.05, .05]) res_ax.set_yticks([-.025, 0, .025]) res_ax.yaxis.tick_right() res_ax.yaxis.set_major_formatter(PercentFormatter(xmax=1, decimals=1)) res_histo_axes.append(res_ax) offset = 0 # offset for i, color in enumerate(colors): # Get the normalized flux for each channel color_data = lc1.loc[lc1.color == color].copy() # Model flux if base_model_flux is None: base_model = np.ones_like(color_data.flux) else: # Mask the sigma clipped frames base_model = base_model_flux.copy() color_data['model'] = base_model # Get the differential flux and error f0 = color_data.flux f0_err = color_data.flux_err f0_index = color_data.index m0 = color_data.model # Flux + offset flux = f0 + offset # Residual residual = flux - base_model # Build dataframe for differntial flux flux_df = pd.DataFrame( { 'flux': flux, 'flux_err': f0_err, 'model': m0, 'residual': residual }, index=f0_index, ).dropna() # Start plotting. # Plot target flux. flux_df.flux.plot( yerr=flux_df.flux_err, marker='o', ls='', alpha=0.15, color=color, ax=lc_ax, rot=0, # Don't rotate date labels legend=False, ) if time_bin is not None: # Time-binned binned_flux_df = flux_df.resample(f'{time_bin}T').apply({ 'flux': np.median, 'flux_err': lambda x: np.sum(x**2) }) # Plot time-binned target flux. binned_flux_df.flux.plot( yerr=binned_flux_df.flux_err, ax=lc_ax, rot=0, marker='o', ms=8, color=color, ls='', label=f'Time-binned - {time_bin}min', legend=False, ) # Plot model flux. flux_df.model.plot( ax=lc_ax, ls='-', color=color, alpha=0.5, lw=3, rot=0, # Don't rotate date labels label='Model fit', legend=True) # Residual scatter flux_df.residual.plot(ax=res_scatter_ax, color=color, ls='', marker='o', alpha=0.5) # Residual histogram axis res_ax = res_histo_axes[i] res_ax.hist(flux_df.residual, orientation='horizontal', color=color, alpha=0.5) res_ax.axhline(0, ls='--', color='k', alpha=0.25) res_ax.set_title(f'σ={flux_df.residual.std():.2%}', y=.82) # Add the offset offset += offset_delta if transit_datetimes is not None: midpoint, ingress, egress = transit_datetimes lc_ax.axvline(midpoint, ls='-.', c='g', alpha=0.5) lc_ax.axvline(ingress, ls='--', c='k', alpha=0.5) lc_ax.axvline(egress, ls='--', c='k', alpha=0.5) if title is not None: fig.suptitle(title, fontsize=18) # Better time axis ticks half_hour = mdates.MinuteLocator(interval=30) h_fmt = mdates.DateFormatter('%H:%M:%S') lc_ax.xaxis.set_major_locator(half_hour) lc_ax.xaxis.set_major_formatter(h_fmt) res_scatter_ax.set_xticks([]) return fig
def plot_scenario_raw(run): rowcnt = 0 axes = [] axcnt = 0 maxy = 0 # +1 for topology plot in the top left x = 9999 # used with LAYOUTS; topology is placed here all_axes = [] layout = LAYOUTS.get(run.get('scenario_switch_cnt')) cols = len(layout[0]) rows = len(layout) fig = plt.figure(constrained_layout=True, figsize=(14, 6)) gs = GridSpec(rows, cols, figure=fig) # first the topology coords = None for y in range(rows): for x in range(cols): if layout[y][x] == 9999: if coords: break coords = [y, x] colspan = sum([1 if v == 9999 else 0 for v in layout[y]]) rowspan = sum([1 if 9999 in v else 0 for v in layout]) break all_axes.append( plt.subplot( gs.new_subplotspec((coords[0], coords[1]), rowspan=rowspan, colspan=colspan))) # and then all the other axes oldval = 0 for y in range(rows): for x in range(cols): val = layout[y][x] if val == 9999: continue if val > oldval: colspan = sum([1 if v == val else 0 for v in layout[y]]) rowspan = sum([1 if val in v else 0 for v in layout]) all_axes.append( plt.subplot( gs.new_subplotspec((y, x), rowspan=rowspan, colspan=colspan))) oldval = val plotted_topo = False for switch in range(0, run.get('scenario_switch_cnt')): #try: # ax = fig.add_subplot(maingrid[rowcnt,axcnt], sharey=axes[0]) #except IndexError: # ax = fig.add_subplot(maingrid[rowcnt,axcnt]) ax = all_axes[switch + 1] axes.append(ax) ax.set_xlim(0, 400) ax.set_ylabel('Flow table utilization') thresh = run.get('scenario_table_capacity') datax = run.get('dts_%d_table_datax' % switch) datay = run.get('dts_%d_table_datay_raw' % switch) if max(datay) > maxy: maxy = max(datay) ax.plot(list(range(-1 * XOFFSET, 0)) + datax, [0] * XOFFSET + datay, color='black', linestyle='-', linewidth=0.75) ax.fill_between(datax, [0] * len(datay), [min(thresh, x) for x in datay], interpolate=True, color='orange', alpha=0.3, label='Rules in flow table') # show bottleneck parameters w1 = str(run.get('scenario_gen_param_topo_bottleneck_cnt')) w2 = str(run.get('scenario_gen_param_topo_bottleneck_duration')) + "s" w3 = str(run.get('scenario_gen_param_topo_bottleneck_intensity')) if run.get('scenario_gen_param_topo_bottleneck_cnt') == 0: w2 = '-' w3 = '-' circled_number = str(switch) circled_color = 'black' scenario_concentrated_switches = run.get( 'scenario_concentrated_switches') if switch in scenario_concentrated_switches: circled_color = 'red' ax.text(0.5, .95, circled_number, fontsize=14, verticalalignment='center', horizontalalignment='center', transform=ax.transAxes, color='white', alpha=1, bbox=dict(boxstyle='circle', facecolor=circled_color, edgecolor='black')) ax.hlines(thresh, 0, 400, color='blue', label="Flow table capacity", linestyle='--', linewidth=1) d2 = 'dts_%d_table_datay_raw' % (switch) d3 = 'dts_%d_table_datay' % (switch) fill_overutil = [True if x > thresh else False for x in datay] ax.fill_between(datax, [thresh] * len(datax), datay, where=fill_overutil, interpolate=True, color='red', alpha=0.2, label='Bottleneck') # plot bottlenecks ax.hlines(-1 * XOFFSET, -1 * XOFFSET, 400, color='gray', linestyle='-', alpha=0.3, linewidth=7) bottleneck_data = run.get('scenario_bottlenecks') set_label = 0 for start, end, details in bottleneck_data: if set_label == 0: ax.hlines(-1 * XOFFSET, start, end, color='red', linestyle='-', alpha=0.3, linewidth=7) set_label = 1 else: ax.hlines(-1 * XOFFSET, start, end, color='red', linestyle='-', alpha=0.3, linewidth=7) # ----------------- plot topology if not yet done (first ax) if not plotted_topo: plotted_topo = True #ax = fig.add_subplot(maingrid[rowcnt+1,axcnt]) hosts_of_switch = {} edges = run.get('scenario_edges') for k, v in run.get('scenario_hosts_of_switch').items(): hosts_of_switch[int(k)] = v plt_switches = list(range(0, run.get('scenario_switch_cnt'))) utils.plot_topo_small(all_axes[0], hosts_of_switch, edges, plt_switches, scenario_concentrated_switches, switch_node_size=250, font_size=15) axcnt += 1 rowcnt += 1 for ax in axes: ax.set_ylim(-120, maxy + 500) ax.spines['top'].set_visible(False) ax.spines['right'].set_visible(False) for ax in axes[-4:]: ax.set_xlabel('Time (s)') for ax in []: ax.set_ylabel('Flow table utilization') handles, labels = axes[-1].get_legend_handles_labels() fig.legend(handles, labels, loc='upper left', ncol=1, fontsize=16) return fig
def make_summary_plot(summary_figure, normalized_spectrum, figure=None): """ :param summary_figure: A dict containing information about how to plot the summary figure :param normalized_spectrum: specutils.Spectrum1D :param figure: matplotlib figure object to make plot in. The function will adjust the figure object If not specified (None), creates a new figure and returns it. """ all_axes_names = [ "top_left", "top_right", "middle", "bottom_left", "bottom_right" ] # Validate file names spectra_filenames = [] Tlit = [] Teff = [] for spectrum_list in summary_figure["spectra_filenames"]: spectra_filenames.append(spectrum_list[0]) Tlit.append(int(spectrum_list[1])) Teff.append(int(spectrum_list[2])) for key in all_axes_names: for spectrum_to_plot in summary_figure[key]["spectra_to_plot"]: assert spectrum_to_plot in spectra_filenames, spectrum_to_plot # Color palette generated from seaborn.color_palette("hls",6) hls_colors = [(0.86, 0.37119999999999997, 0.33999999999999997), (0.82879999999999987, 0.86, 0.33999999999999997), (0.33999999999999997, 0.86, 0.37119999999999997), (0.33999999999999997, 0.82879999999999987, 0.86), (0.37119999999999997, 0.33999999999999997, 0.86), (0.86, 0.33999999999999997, 0.82879999999999987)] # Load spectra spectra_objects = {} spectra_colors = {} # HACK data path data_dir = os.path.dirname(os.path.abspath(__file__)) + "/data/spectra" for i, spectrum_filename in enumerate(spectra_filenames): fname = "{}/{}.fits".format(data_dir, spectrum_filename) if os.path.exists(fname): spectra_objects[spectrum_filename] = specutils.Spectrum1D.read( fname) spectra_colors[spectrum_filename] = hls_colors[i % len(hls_colors)] else: logger.warn("Could not find spectrum data file {}".format(fname)) # Make figure object and axes if figure == None: figure = plt.figure(figsize=(10, 8)) figure.subplots_adjust(left=0.10, right=0.95) figure.patch.set_facecolor("w") gs = GridSpec(4, 2) gs.update(top=0.77) ax_top_left = figure.add_subplot(gs.new_subplotspec((0, 0), rowspan=2)) ax_top_right = figure.add_subplot(gs.new_subplotspec((0, 1), rowspan=2)) ax_middle = figure.add_subplot(gs.new_subplotspec((2, 0), colspan=2)) ax_bot_left = figure.add_subplot(gs.new_subplotspec((3, 0))) ax_bot_right = figure.add_subplot(gs.new_subplotspec((3, 1))) all_axes = [ ax_top_left, ax_top_right, ax_middle, ax_bot_left, ax_bot_right ] # HACK def _label_Teff(ax, spectra_filenames, Tlit, Teff): ii = np.argsort(Tlit) spectra_filenames = list(np.array(spectra_filenames)[ii]) Tlit = list(np.array(Tlit)[ii]) Teff = list(np.array(Teff)[ii]) temp_lit = [[r"$T_{\rm lit}$", 'k']] temp_eff = [[r"$T_{\rm eff}$", 'k']] for spec_name, _Tlit, _Teff in zip(spectra_filenames, Tlit, Teff): temp_lit.append([str(_Tlit), spectra_colors[spec_name]]) temp_eff.append([str(_Teff), spectra_colors[spec_name]]) print(temp_lit) print(temp_eff) coord = 100 for i, (entrylit, entryeff) in enumerate(zip(temp_lit, temp_eff)): ax.annotate(entrylit[0], xy=(4858.33, 0), xytext=(40, coord), textcoords='offset points', size=10, color=entrylit[1]) ax.annotate(entryeff[0], xy=(4858.33, 0), xytext=(270, coord), textcoords='offset points', size=10, color=entryeff[1]) coord -= 15 # Plot for key, ax in zip(all_axes_names, all_axes): ax_dict = summary_figure[key] this_star, = ax.plot(normalized_spectrum.dispersion, normalized_spectrum.flux, 'k') for spec_name in ax_dict["spectra_to_plot"]: spec = spectra_objects[spec_name] ax.plot(spec.dispersion, spec.flux, color=spectra_colors[spec_name]) ax.set_ylabel(ax_dict["label"]) ax.set_xlim(ax_dict["wavelength_range"]) ax.set_ylim(ax_dict["ylim"]) formatter = plt.matplotlib.ticker.ScalarFormatter(useOffset=False) ax.xaxis.set_major_formatter(formatter) if ax_dict["label"] == "H-beta": _label_Teff(ax, spectra_filenames, Tlit, Teff) handles = [this_star] labels = ["This star"] for i, spec_name in enumerate(spectra_filenames): color = spectra_colors[spec_name] artist = plt.Line2D((0, 1), (0, 0), color=color) handles.append(artist) labels.append(spec_name) figure.legend(handles, labels, (.6, .8), prop={'size': 12}, ncol=2) return figure
def plot_log(log: LogFile): np_data = log.data.to_numpy() func_data = {} for row in np_data: func_name, ts, te = row[:3] exec_time = te - ts if func_name in func_data: func_data[func_name]['num_calls'] += 1 func_data[func_name]['total_exec_time'] += exec_time last_min = func_data[func_name]['min'] func_data[func_name]['min'] = min(exec_time, last_min) last_max = func_data[func_name]['max'] func_data[func_name]['max'] = max(exec_time, last_max) else: func_data[func_name] = { 'num_calls': 1, 'total_exec_time': exec_time, 'min': exec_time, 'max': exec_time, } for func_name in func_data: # calculate and average total_exec_time = func_data[func_name]['total_exec_time'] num_calls = func_data[func_name]['num_calls'] func_data[func_name]['avg'] = total_exec_time / num_calls fig = plt.figure(figsize=(12, 12)) # use GridSpec for more organized layout # https://matplotlib.org/3.2.1/gallery/subplots_axes_and_figures/gridspec_multicolumn.html gs = GridSpec(2, 2, figure=fig) # Plot 1: total amount of time for each methods # https://matplotlib.org/tutorials/introductory/pyplot.html#plotting-with-categorical-variables ax = plt.subplot(gs.new_subplotspec((0, 0))) ax.set_title('total amount of execution time') names = [] values = [] for func_name in func_data: names.append(func_name) values.append(func_data[func_name]['total_exec_time']) bars = ax.bar(names, values) plot_values_on_top_of_bars( ax=ax, bars=bars, values=[f'{x:.2f}' for x in values], max_bar_height=max(values), ) # Plot 2: number of calls for each methods ax = plt.subplot(gs.new_subplotspec((0, 1))) ax.set_title('number of calls') names = [] values = [] for func_name in func_data: names.append(func_name) values.append(func_data[func_name]['num_calls']) bars = ax.bar(names, values) plot_values_on_top_of_bars( ax=ax, bars=bars, values=[repr(x) for x in values], max_bar_height=max(values), ) # Plot 3: plot max, min, and average for each methods # We use grouped barplot here. # https://python-graph-gallery.com/11-grouped-barplot/ ax = plt.subplot(gs.new_subplotspec((1, 0), colspan=2)) ax.set_title('max, min, and avg execution time') min_bars = [] max_bars = [] avg_bars = [] group_labels = [] for func_name in func_data: min_bars.append(func_data[func_name]['min']) max_bars.append(func_data[func_name]['max']) avg_bars.append(func_data[func_name]['avg']) group_labels.append(func_name) bar_width = .25 # bar width * (number of group + 1) for x-axis spacing # 1 unit for spacing min_bars_xs = np.arange(len(min_bars)) * (bar_width * (3 + 1)) avg_bars_xs = [bar_width + x for x in min_bars_xs] max_bars_xs = [bar_width + x for x in avg_bars_xs] bars = ax.bar( x=min_bars_xs, height=min_bars, color='#ff0000', width=bar_width, label='min', ) plot_values_on_top_of_bars( ax=ax, bars=bars, values=[f'{x:.4f}' for x in min_bars], max_bar_height=max(max_bars), ) bars = ax.bar( x=avg_bars_xs, height=avg_bars, color='#00ff00', width=bar_width, label='avg', ) plot_values_on_top_of_bars( ax=ax, bars=bars, values=[f'{x:.4f}' for x in avg_bars], max_bar_height=max(max_bars), ) bars = ax.bar( x=max_bars_xs, height=max_bars, color='#0000ff', width=bar_width, label='max', ) plot_values_on_top_of_bars( ax=ax, bars=bars, values=[f'{x:.5f}' for x in max_bars], max_bar_height=max(max_bars), ) # group label x position to middle bar ax.set_xticks(avg_bars_xs) ax.set_xticklabels(group_labels) ax.legend() plt.show()
Brune = (2. * np.pi * (f_bins) * omega0) / (1. + ((1. / fc) * f_bins)**2.) shift = np.mean(np.log10(event_spec[27:70]) - np.log10(Brune[27:70])) # Brune = 10.**(np.log10(Brune)+shift) # plot the station spectra fig = plt.figure(figsize=(22, 14)) plt.suptitle('event ' + eventid + ', magnitude ' + str(ml) + ', recorded on station ' + station + ', distance ' + str(round(dist_km, 2)) + ' km ') plt.tight_layout(pad=0.01, w_pad=0.01, h_pad=0.01) plt.subplots_adjust(left=0.06, right=0.99, top=0.92, bottom=0.05) gs = GridSpec(3, 2) plt.subplot(gs.new_subplotspec((0, 0), colspan=1)) # plt.title('event ' + eventid + ', magnitude ' + str(ml) + ', recorded on station ' + station + ', distance ' + str(round(dist_km,2)) + ' km ') x = np.arange(0, len(dataE), 1) / 100. plt.plot(x, dataE, color='black', label='EW') # plt.plot(x, dataN, color = 'red', label = 'NS') plt.xlim(-2, 65) plt.legend(loc=1, borderaxespad=0.) plt.gca().yaxis.get_major_formatter().set_powerlimits((0, 1)) plt.ylabel('Velocity (m/s)') plt.ylim(min(dataN), max(dataN)) plt.annotate('seconds', va='center', xy=(0.48, -0.12), xycoords='axes fraction') plt.annotate('(a)',
def lpf_event_display(xhit, nhit, fit_result, hit_is_used, xiter, **kwargs): """ Event display :param xhit: :param nhit: :param fit_result: :param hit-is_used: :param xiter: :param kwargs: :return: """ xhit = np.array(xhit) nhit = np.array(nhit) plot_range = kwargs.pop('range', None) zoom = kwargs.pop('zoom', -1) nbins = kwargs.pop('nbins', 15) if plot_range == 'None': plot_range = ((0, 100), (0, 100)) if zoom > 0: plot_range = ((fit_result[0] - zoom / 2, fit_result[0] + zoom / 2), (fit_result[1] - zoom / 2, fit_result[1] + zoom / 2)) print("Reconstruction::lpf_event_display() ") fig = plt.figure(figsize=(16, 6)) gs = GridSpec(2, 2, figure=fig) ax0 = plt.subplot(gs.new_subplotspec((0, 0), rowspan=2)) ax1 = plt.subplot(gs.new_subplotspec((0, 1), rowspan=1)) ax2 = plt.subplot(gs.new_subplotspec((1, 1), rowspan=1)) # ax1 = plt.subplot(222) # ax2 = plt.subplot(224) # fig, ax0 = plt.subplots(nrows=1) # make a list of the intermediate steps xp = [] yp = [] nn = [] iiter = [] for i in range(len(xiter)): if xiter[i][3] != 0: xp.append(xiter[i][0]) yp.append(xiter[i][1]) nn.append(xiter[i][2]) iiter.append(i) xp = np.array(xp) yp = np.array(yp) nn = np.array(nn) iiter = np.array(iiter) niter = len(xp) ax1.plot(iiter, xp - fit_result[0]) ax1.plot(iiter, yp - fit_result[1]) ax1.set_xlabel('iteration') ax2.plot(iiter, nn) ax2.set_xlabel('iteration') # make these smaller to increase the resolution dx, dy = (plot_range[0][1] - plot_range[0][0]) / 400, ( plot_range[1][1] - plot_range[1][0]) / 400 # generate 2 2d grids for the x & y bounds x = np.arange(plot_range[0][0], plot_range[0][1], dx) y = np.arange(plot_range[1][0], plot_range[1][1], dy) z = np.zeros((len(y), len(x))) #print(x,y) for i in range(len(x)): for j in range(len(y)): xx = x[i] yy = y[j] xff = np.array([xx, yy, 0]) #print('xfit =',xff,' r0 =',xiter[niter-1][2]) z[j][i] = lpf_lnlike_plot(xhit, nhit, hit_is_used, xff, xiter[niter - 1][2]) # z = z[:-1, :-1] levels = MaxNLocator(nbins=nbins).tick_values(z.min(), z.max()) # cmap = plt.get_cmap('afmhot') cmap = plt.get_cmap('PiYG') # norm = BoundaryNorm(levels, ncolors=cmap.N, clip=True) # ax0 = fig.gca() cf = ax0.contourf(x + dx / 2., y + dy / 2., z, levels=levels, cmap=cmap) fig.colorbar(cf, ax=ax0) title_string = 'x = {:8.2f} y = {:8.2f} r0= {:8.2f}'.format( fit_result[0], fit_result[1], fit_result[2]) ax0.set_title(title_string) # add the light detectors mx_eff = -1 for ih in range(len(nhit)): if nhit[ih] > mx_eff: mx_eff = nhit[ih] for ih in range(len(nhit)): # draw location of SiPM xs = xhit[ih] # plot sensor only if in range if (xs[0] > plot_range[0][0]) & (xs[0] < plot_range[0][1]) & \ (xs[1] > plot_range[1][0]) & (xs[1] < plot_range[1][1]): #dx = nhit[ih] / mx_eff *10 rr = (nhit[ih] + 0.25) / mx_eff * 10 #sq = plt.Rectangle(xy=(xs[0] - dx / 2, xs[1] - dx / 2), # height=dx, # width=dx, # fill=False, color='red') if nhit[ih] > 0: if hit_is_used[ih]: color = 'red' else: color = 'black' sq = plt.Circle(xy=(xs[0], xs[1]), radius=rr, fill=False, color=color) else: sq = plt.Circle(xy=(xs[0], xs[1]), radius=rr, fill=False, color='black') ax0.add_artist(sq) # write number of detected photons ### txs = str(nhit[ih]) ### ax0.text(xs[0] + dx / 2 + 2.5, xs[1], txs, color='red') # initial position ax0.plot(xiter[0][0], xiter[0][1], 'o', markersize=10, color='cyan') ax0.plot(xp, yp, 'w-o', markersize=5) # true position # plt.plot(self.sim.get_x0()[0], self.sim.get_x0()[1], 'x', markersize=14, color='cyan') # reconstructed position # if abs(self.fdata['xr']) < 100: ax0.plot(fit_result[0], fit_result[1], 'wo', markersize=10) ax0.set_xlabel('x (mm)', fontsize=18) ax0.set_ylabel('y (mm)', fontsize=18) ax0.set_xlim([plot_range[0][0], plot_range[0][1]]) ax0.set_ylim([plot_range[1][0], plot_range[1][1]]) plt.show() istat = int(input("Type: 0 to continue, 1 to make pdf, 2 to quit....")) if istat == 1: fname = 'event.pdf' fig.savefig(fname) fname = 'event.png' fig.savefig(fname) clear_output() return istat
def plot_cplap_ternary(output='plot-2d.pdf', grid_file='grid.dat', txt_file='2Dplot.txt', xmin=None, ymin=None, style=['ggplot'], cmap='viridis', width=6, height=4, ratio=[4], gridlines=None): # Set Truetype PDF/PS fonts unless overruled by style file matplotlib.rcParams['pdf.fonttype'] = 42 matplotlib.rcParams['ps.fonttype'] = 42 if len(style) > 0: matplotlib.style.use(style) fig = plt.figure(figsize=(width, height)) if len(ratio) == 1: ratio += [1] elif len(ratio) > 2: raise ValueError('Ratio can be given as one or two integers. ' '{} is too many!'.format(len(ratio))) gs = GridSpec(1, ratio[0] + ratio[1]) ax = fig.add_subplot(gs.new_subplotspec((0, ratio[1]), colspan=ratio[0])) cax = fig.add_subplot(gs.new_subplotspec((0, 0), colspan=ratio[1])) with open('grid.dat', 'rt') as f: # Scroll to formula and read for _ in range(3): line = f.readline() el_matches = re.findall(r'\d+ (\w+)', line) # Scroll to number of points and read for _ in range(4): line = f.readline() npts = 5 npts_matches = re.findall(r'first\s+(\d+) points', line) if len(npts_matches) == 1: npts = int(npts_matches[0]) else: raise Exception("Couldn't read number of polyhedron corners") # Scroll to data lines and read coordinates from npts lines for _ in range(5): f.readline() region = np.zeros((npts, 2)) for i in range(npts): line = f.readline().split() x, y = float(line[0]), float(line[1]) region[i, :] = x, y # # Use convex hull solver to draw polyhedron edges in correct order # hull = np.array([region[i] for i in ConvexHull(region).vertices]) # region_patch = Polygon(hull, facecolor=(0.6, 0.6, 0.6)) # ax.add_patch(region_patch) # Read in rest of mesh, skipping header, region and '|' column mesh = np.genfromtxt('grid.dat', skip_header=(12 + npts), usecols=(0, 1, 3)) mesh_x = sorted(set(mesh[:, 0])) mesh_y = sorted(set(mesh[:, 1])) mesh_z = np.zeros((len(mesh_y), len(mesh_x))) * np.NaN for x, y, z in mesh: ix = mesh_x.index(x) iy = mesh_y.index(y) mesh_z[iy, ix] = z mesh_z = np.ma.masked_invalid(mesh_z) dep_mu = ax.pcolormesh(mesh_x, mesh_y, mesh_z, rasterized=True, cmap=cmap) cbar = fig.colorbar(dep_mu, cax=cax) cbar.set_label(r'$\mu$ ({}) / eV'.format(el_matches[2])) with open('2Dplot.txt', 'rt') as f: lines = f.readlines() data = OrderedDict() for i in range(len(lines) // 4 + 1): species = lines[i * 4][1:-1] x1, y1 = map(float, lines[i * 4 + 1].split()) x2, y2 = map(float, lines[i * 4 + 2].split()) data[species] = [[x1, x2], [y1, y2]] if xmin is None: xmin = ceil(min(min(coords[0]) for coords in data.values())) if ymin is None: ymin = ceil(min(min(coords[1]) for coords in data.values())) for species, (x, y) in data.items(): ax.plot(x, y, '-', label=format_chem(species)) ax.legend() ax.set_xlim(xmin, 0) ax.set_ylim(ymin, 0) ax.set_xlabel(r'$\mu$ ({}) / eV'.format(el_matches[0])) ax.xaxis.set_label_position('top') ax.xaxis.set_ticks_position('top') ax.set_ylabel(r'$\mu$ ({}) / eV'.format(el_matches[1])) ax.yaxis.set_label_position('right') ax.yaxis.set_ticks_position('right') # Gridlines option can overrule style defaults if gridlines is not None: ax.grid(gridlines) fig.tight_layout() if output is None: plt.show() else: fig.savefig(output)
def zernikePyramid(xs, ys, zs, figsize=(13, 8), vmin=-1, vmax=1, vdim=True, s=5, title=None, filename=None, fig=None, **kwargs): """Make a multi-zernike plot in a pyramid shape. Subplots show individual Zernikes over a range of x and y (presumably a field of view). Parameters ---------- xs, ys: array of float Field angles (or other spatial coordinate over which to plot Zernikes) zs: array of float, shape (jmax, xymax) Zernike values. First index labels the particular Zernike coefficient, second index labels spatial coordinate. First index implicitly starts at j=4 defocus. """ import warnings import galsim jmax = zs.shape[0] + 3 nmax, _ = galsim.zernike.noll_to_zern(jmax) nrow = nmax - 1 ncol = nrow + 2 gridspec = GridSpec(nrow, ncol) def shift(pos, amt): return [pos.x0 + amt, pos.y0, pos.width, pos.height] def shiftAxes(axes, amt): for ax in axes: ax.set_position(shift(ax.get_position(), amt)) if fig is None: fig = Figure(figsize=figsize, **kwargs) axes = {} shiftLeft = [] shiftRight = [] for j in range(4, jmax + 1): n, m = galsim.zernike.noll_to_zern(j) if n % 2 == 0: row, col = n - 2, m // 2 + ncol // 2 else: row, col = n - 2, (m - 1) // 2 + ncol // 2 subplotspec = gridspec.new_subplotspec((row, col)) axes[j] = fig.add_subplot(subplotspec) axes[j].set_aspect('equal') if nrow % 2 == 0 and n % 2 == 0: shiftLeft.append(axes[j]) if nrow % 2 == 1 and n % 2 == 1: shiftRight.append(axes[j]) cbar = {} for j, ax in axes.items(): n, _ = galsim.zernike.noll_to_zern(j) ax.set_title("Z{}".format(j)) if vdim: _vmin = vmin / n _vmax = vmax / n else: _vmin = vmin _vmax = vmax scat = ax.scatter(xs, ys, c=zs[j - 4], s=s, linewidths=0.5, cmap='Spectral_r', rasterized=True, vmin=_vmin, vmax=_vmax) cbar[j] = fig.colorbar(scat, ax=ax) ax.set_xticks([]) ax.set_yticks([]) if title: fig.suptitle(title, x=0.1) # Mistakenly raises MatplotlibDeprecationWarning. # See https://github.com/matplotlib/matplotlib/issues/19486 with warnings.catch_warnings(): warnings.simplefilter("ignore") fig.tight_layout() amt = 0.5 * (axes[4].get_position().x0 - axes[5].get_position().x0) shiftAxes(shiftLeft, -amt) shiftAxes(shiftRight, amt) shiftAxes([cbar[j].ax for j in cbar.keys() if axes[j] in shiftLeft], -amt) shiftAxes([cbar[j].ax for j in cbar.keys() if axes[j] in shiftRight], amt) if filename: fig.savefig(filename) return fig
def add_subplot(location, rowspan=1, colspan=1): gridspec = GridSpec(2, 3) subplotspec = gridspec.new_subplotspec(location, rowspan, colspan) return fig.add_subplot(subplotspec)
def zernikePyramid(xs, ys, zs, figsize=(13, 8), vmin=-1, vmax=1, vdim=True, s=5, title=None, filename=None, fig=None, **kwargs): import galsim jmax = zs.shape[0] + 3 nmax, _ = galsim.zernike.noll_to_zern(jmax) nrow = nmax - 1 ncol = nrow + 2 gridspec = GridSpec(nrow, ncol) def shift(pos, amt): return [pos.x0 + amt, pos.y0, pos.width, pos.height] def shiftAxes(axes, amt): for ax in axes: ax.set_position(shift(ax.get_position(), amt)) if fig is None: fig = Figure(figsize=figsize, **kwargs) axes = {} shiftLeft = [] shiftRight = [] for j in range(4, jmax + 1): n, m = galsim.zernike.noll_to_zern(j) if n % 2 == 0: row, col = n - 2, m // 2 + ncol // 2 else: row, col = n - 2, (m - 1) // 2 + ncol // 2 subplotspec = gridspec.new_subplotspec((row, col)) axes[j] = fig.add_subplot(subplotspec) axes[j].set_aspect('equal') if nrow % 2 == 0 and n % 2 == 0: shiftLeft.append(axes[j]) if nrow % 2 == 1 and n % 2 == 1: shiftRight.append(axes[j]) cbar = {} for j, ax in axes.items(): n, _ = galsim.zernike.noll_to_zern(j) ax.set_title("Z{}".format(j)) if vdim: _vmin = vmin / n _vmax = vmax / n else: _vmin = vmin _vmax = vmax scat = ax.scatter(xs, ys, c=zs[j - 4], s=s, linewidths=0.5, cmap='Spectral_r', rasterized=True, vmin=_vmin, vmax=_vmax) cbar[j] = fig.colorbar(scat, ax=ax) ax.set_xticks([]) ax.set_yticks([]) if title: fig.suptitle(title, x=0.1) fig.tight_layout() amt = 0.5 * (axes[4].get_position().x0 - axes[5].get_position().x0) shiftAxes(shiftLeft, -amt) shiftAxes(shiftRight, amt) shiftAxes([cbar[j].ax for j in cbar.keys() if axes[j] in shiftLeft], -amt) shiftAxes([cbar[j].ax for j in cbar.keys() if axes[j] in shiftRight], amt) if filename: fig.savefig(filename) return fig
def add_subplot(location, rowspan=1, colspan=1): gridspec = GridSpec(2, 3) subplotspec = gridspec.new_subplotspec(location, rowspan, colspan) return fig.add_subplot(subplotspec)
return dec_to_clk(time_dec) fig = plt.figure(figsize=(10, 6), num='Sunrise / Sunset') plt.subplots_adjust(top=.925, left=0.100, right=.950, wspace=0.1) gs = GridSpec(28, 28, figure=fig) # date list for x axis of all plots base = datetime.strptime(str(year) + '0101', '%Y%m%d') date_list = [base + timedelta(days=x) for x in range(0, num_days)] # main plot y_rise = [i.sunrise_dec for i in data_dst] y_set = [i.sunset_dec for i in data_dst] y_solar_noon = [i.solar_noon_dec for i in data_dst] ax_0_0 = plt.subplot(gs.new_subplotspec((0, 2), colspan=25, rowspan=10)) ax_0_0.set_title(plot_title) ax_0_0.grid(which='major', linestyle='-', linewidth=0.5, color='grey') ax_0_0.set_xlabel('Day of Year') ax_0_0.xaxis.set_major_locator(mdates.MonthLocator()) ax_0_0.xaxis.set_major_formatter(mdates.DateFormatter('%b')) ax_0_0.xaxis.set_minor_locator(mdates.DayLocator()) ax_0_0.set_ylabel('Time (24-hour)') ax_0_0.yaxis.set_major_formatter(tick.FuncFormatter(dec_to_clk_ff)) ax_0_0.set_ylim(0, 24) ax_0_0.plot(date_list, y_rise, 'b') ax_0_0.plot(date_list, y_set, 'r') ax_0_0.plot(date_list, y_solar_noon, 'k-.', label='Solar Noon') ax_0_0.legend(loc='best', fontsize='small') # Day Length
def plot_field_map(model, feature, radius, **kwargs): """ This function plots the synthetic values generated by a given spherical harmonic model within the domain of geomagnetism. It computes the design matrix G, based on the length of the input model, m, and uses it in the forward problem: d = G.m The user has several options for plotting different field features in different plotting views. This function serves well as a first investigation of a given model, but it is not flexible for more advanced visualisation goals. The user is encouraged to visit https://scitools.org.uk/cartopy for learning how to use cartopy for plotting, which is relatively simply. The complexity of the below function is due to the different options given, but a cartopy map projection can actually be carried out in a few lines of code. Args: model (ndarray): model coefficients used for computing d = G.m, where m is the model feature (str): geomagnetic field feature to be plotted, options: 'B_r', 'B_t', 'B_p', 'F', 'D', 'I' or 'H' radius (float): the radius at which the synthetic field values should be generated **kwargs (optional): value_limits (float list): upper and lower value limits e.g. [-1e3, 1e3] mesh_size (float): mesh size for the synthetic grid, below .5 computations are heavy lat_limits (float list): limits on latitude, order does not matter e.g. [90, -90] lon_limits (float list): limits on longitude, order does not matter e.g. [-180, 180] main_projection (object): Cartopy projection object e.g. ccrs.Mollweide() for full list of projections see: https://scitools.org.uk/cartopy plot_poles (boolean): Whether to plot poles or not, default is True polar_limit (float): Bounding latitude for the polar plots default is 60N and 60S contour_labels (float list): list of contour line labels plotted if feature=='D' e.g. [-30, -15, -5, 0, 5, 15, 30] microtesla (boolean): Set to false for plotting in nanoTesla savefig (boolean): save figure True/False colormap (str): Choose from matplotlibs color map options e.g. 'PuOr_r' or 'RdBu' title_string (str): set a customized title string colorbar_string (str): set a customized colorbar string figure_size (float tuple): figure size, (width, height) in inches. title_pos (float): position of the title text, e.g. 1.1 label_pos (int): spacing in points between the colobar label and the x-axis. Returns: None Notes: - Contour lines are only plotted on declination plots - Contour lines are omitted in polar plots. Calling the function with plot_poles=False and projection_type=ccrs.LambertAzimuthalEqualArea(), will produce a polar plot with contours. Examples: # Example1 model = np.loadtxt('coefficients_L2.txt') plot_feature = 'B_r' radius_core = 3480. plot_field_map(model, plot_feature, radius_core) # Example2: plot_feature = 'D' radius_surface = 6371.2 plot_field_map(model, plot_feature, radius_surface, value_limits=[-40, 40], no_poles=True, colormap='RdBu') @author: Eigil Y. H. Lippert, Student DTU Space, <*****@*****.**> """ # set default values value_limits = [-1e3, 1e3] mesh_size = 1 lat_limits = [90, -90] lon_limits = [-180, 180] main_projection = ccrs.Mollweide() plot_poles = True polar_limit = 60 contour_labels = [-30, -15, -5, 0, 5, 15, 30] microtesla = True savefig = False colormap = 'PuOr_r' title_string = None colorbar_string = None figure_size = (12, 12) title_pos = 1. label_pos = 5. # update defaults based on used input for key, value in kwargs.items(): if key == 'value_limits': value_limits = value elif key == 'mesh_size': mesh_size = value elif key == 'lat_limits': lat_limits = value elif key == 'lon_limits': lon_limits = value elif key == 'main_projection': main_projection = value elif key == 'plot_poles': plot_poles = value elif key == 'polar_limit': polar_limit = value elif key == 'contour_labels': contour_labels = value elif key == 'microtesla': microtesla = value elif key == 'savefig': savefig = value elif key == 'colormap': colormap = value elif key == 'title_string': title_string = value elif key == 'colorbar_string': colorbar_string = value elif key == 'figure_size': figure_size = value elif key == 'title_pos': title_pos = value elif key == 'label_pos': label_pos = value # set constants degree = int(-1 + np.sqrt(1 + len(model))) r_surface = 6371.2 rad = np.pi / 180 lat_bound = [np.max(lat_limits), np.min(lat_limits)] lon_bound = [np.min(lon_limits), np.max(lon_limits)] # make range of lat/lon lat = 90 - np.arange(lat_bound[0], lat_bound[1] - mesh_size, -mesh_size) # lat/theta array between 90 and 90 lon = np.arange(lon_bound[0], lon_bound[1] + mesh_size, mesh_size) # remove pole points lat = np.delete(lat, np.where(lat == 0)) lat = np.delete(lat, np.where(lat == 180.)) # compute(lat, lon) - grid lon_grid, lat_grid = np.meshgrid(lon, lat) rows, cols = np.shape(lon_grid) # reshape for design_SHA to work lon_grid = lon_grid.reshape(-1, ) lat_grid = lat_grid.reshape(-1, ) [Gr, Gt, Gp] = design_SHA(radius / r_surface, lat_grid * rad, lon_grid * rad, degree) G = np.vstack((Gr, Gt, Gp)) # compute synthetic field B_synth = G.dot(model) # seperate into components step = int(len(B_synth) / 3) Br_synth = B_synth[0:step] Bt_synth = B_synth[step:step * 2] Bp_synth = B_synth[step * 2::] # reshape back for pcolormesh to work lon_grid = lon_grid.reshape(rows, cols) lat_grid = (90 - lat_grid).reshape(rows, cols) # reshape field components into size of grid as well Br_synth = Br_synth.reshape(rows, cols) Bt_synth = Bt_synth.reshape(rows, cols) Bp_synth = Bp_synth.reshape(rows, cols) # chosen feature: for feature_name in [feature]: if feature_name == 'B_r': feature_name = feature_name + '-component' # compute Br component feat = Br_synth unit = 'B_r, [nT]' if microtesla: feat = feat * 1e-3 unit = 'B_r, [\mu T]' elif feature_name == 'B_t': feature_name = feature_name + '-component' # compute Bt component feat = Bt_synth unit = 'B_t, [nT]' if microtesla: feat = feat * 1e-3 unit = 'B_t, [\mu T]' elif feature_name == 'B_p': feature_name = feature_name + '-component' # compute Bp component feat = Bp_synth unit = 'B_p, [nT]' if microtesla: feat = feat * 1e-3 unit = 'B_p, [\mu T]' elif feature_name == 'F': feature_name = feature_name + ', field intensity' # compute F, intensity feat = np.sqrt(Br_synth ** 2 + Bt_synth ** 2 + Bp_synth ** 2) unit = 'F, [nT]' if microtesla: feat = feat * 1e-3 unit = 'F, [\mu T]' elif feature_name == 'D': feature_name = feature_name + ', declination' X_synth = -Bt_synth Y_synth = Bp_synth # compute D, declination feat = np.arctan2(Y_synth, X_synth) * 180 / np.pi unit = 'D, [degree]' elif feature_name == 'I': feature_name = feature_name + ', inclination' X_synth = -Bt_synth Y_synth = Bp_synth Z_synth = -Br_synth H_synth = np.sqrt(X_synth ** 2 + Y_synth ** 2) # compute I, inclination feat = np.arctan2(Z_synth, H_synth) * 180 / np.pi unit = 'I, [degree]' elif feature_name == 'H': feature_name = feature_name + ', horisontal component' X_synth = -Bt_synth Y_synth = Bp_synth # compute H, horisontal component feat = np.sqrt(X_synth ** 2 + Y_synth ** 2) unit = 'H, [nT]' if microtesla: feat = feat * 1e-3 unit = 'H, [\mu T]' else: print('Feature not known please choose B_r, B_t, B_p, F, D, I or H') # creates a list of projections for a combined main projection polar projection figure projections = [main_projection, ccrs.LambertAzimuthalEqualArea(central_longitude=0., central_latitude=90.), ccrs.LambertAzimuthalEqualArea(central_longitude=0., central_latitude=-90.)] # if no poles, only use one figure position if not plot_poles: subplot_position = [(0, 0)] else: subplot_position = [(0, 0), (2, 0), (2, 2)] colspan = 4 f = plt.figure(figsize=figure_size) gs = GridSpec(4, 4, figure=f) for i, pos in enumerate(subplot_position): # change colspan for polar plots if i > 0: colspan = 2 if not plot_poles: ax = plt.subplot(projection=projections[0]) else: ax = plt.subplot(gs.new_subplotspec(pos, colspan=colspan, rowspan=2), projection=projections[i]) # select polar values of interest for pcolormesh. if (i == 1) or (i == 2): lat_bound = [(90, 60), (-90, -60)] if i == 1: lat_bound = [90, polar_limit] polar_mask = lat_grid >= lat_bound[1] elif i == 2: lat_bound = [-90, -polar_limit] polar_mask = lat_grid <= lat_bound[1] # the masked array is 1-d so reshape with same number of columns as before: lat_grid_polar = np.reshape(lat_grid[polar_mask], (-1, lat_grid.shape[1])) b_r_polar = np.reshape(feat[polar_mask], (-1, lon_grid.shape[1])) lon_grid_polar = lon_grid[0:lat_grid_polar.shape[0], :] h1 = ax.pcolormesh(lon_grid_polar, lat_grid_polar, b_r_polar, cmap=colormap, transform=ccrs.PlateCarree(), vmin=value_limits[0], vmax=value_limits[1]) ax.set_extent([-180, 180, lat_bound[0], lat_bound[1]], ccrs.PlateCarree()) # make circular boundary on projection theta = np.linspace(0, 2 * np.pi, 100) center, radius = [0.5, 0.5], 0.5 verts = np.vstack([np.sin(theta), np.cos(theta)]).T circle = mpath.Path(verts * radius + center) ax.set_boundary(circle, transform=ax.transAxes) else: # If declination draw contour lines if unit == 'D, [degree]': feat_flatten = feat.flatten() lon_grid_flatten = lon_grid.flatten() lat_grid_flatten = lat_grid.flatten() h1 = ax.scatter(x=lon_grid_flatten, y=lat_grid_flatten, s=20, c=feat_flatten, edgecolors='none', transform=ccrs.PlateCarree(), cmap=colormap, vmin=value_limits[0], vmax=value_limits[1]) c1 = ax.contour(lon, 90 - lat, feat, contour_labels, colors='black', linewidths=2.5, linestyles='solid', alpha=0.6, transform=ccrs.PlateCarree()) cl = plt.clabel(c1, fontsize=10, colors='k', inline=1, inline_spacing=8, fmt='%i', rightside_up=True, use_clabeltext=True) else: h1 = ax.pcolormesh(lon_grid, lat_grid, feat, cmap=colormap, transform=ccrs.PlateCarree(), vmin=value_limits[0], vmax=value_limits[1]) ax.coastlines(linewidth=1.1) ax.gridlines() # we need to set axes_class=plt.Axes, else it attempts to create a GeoAxes as colorbar if i == 0: divider = make_axes_locatable(ax) ax_cb = divider.new_vertical(size="5%", pad=0.1, axes_class=plt.Axes, pack_start=True) f.add_axes(ax_cb) # colorbar and properties cbar = plt.colorbar(h1, cax=ax_cb, orientation="horizontal") if colorbar_string is None: colorbar_string = r'${}$'.format(unit) cbar.set_label(colorbar_string, rotation=0, labelpad=label_pos, fontsize='xx-large') cbar.ax.tick_params(labelsize=15) if title_string is None: title_string = 'Field map of {}'.format(feature_name) ax.set_title(title_string, weight='bold', fontsize='xx-large', y=title_pos) if savefig: plt.savefig('Field_map_of_the_{}_component'.format(feature_name) + '.png') plt.show() return
def __calculate_layout(self): ''' Creates the subplot specs for the chart layout, options are 3 panes, horizontal, split right ------------------- | | | | |--------| | | | ------------------- 3 panes, horizontal, split left ------------------- | | | |--------| | | | | ------------------- 3 panes, vertical, split bottom ------------------- | | |-----------------| | | | ------------------- 3 panes, vertical, split top ------------------- | | | |-----------------| | | ------------------- 2 panes, vertical ------------------- | | |-----------------| | | ------------------- 2 panes, horizontal ------------------- | | | | | | | | | ------------------- 1 pane ------------------- | | | | | | ------------------- :return: image_spec, chart_spec, filter_spec ''' layout = self.chartLayout.currentText() filter_spec = None image_spec = None chart_spec = None if layout == "Image | Chart, Filters": image_spec, chart_spec, filter_spec = self.__get_one_pane_two_pane_spec( ) elif layout == "Image | Filters, Chart": image_spec, filter_spec, chart_spec = self.__get_one_pane_two_pane_spec( ) elif layout == "Chart | Image, Filter": chart_spec, image_spec, filter_spec = self.__get_one_pane_two_pane_spec( ) elif layout == "Chart | Filters, Image": chart_spec, filter_spec, image_spec = self.__get_one_pane_two_pane_spec( ) elif layout == "Filters | Image, Chart": filter_spec, image_spec, chart_spec = self.__get_one_pane_two_pane_spec( ) elif layout == "Filters | Chart, Image": filter_spec, chart_spec, image_spec = self.__get_one_pane_two_pane_spec( ) elif layout == 'Image, Filters | Chart': image_spec, filter_spec, chart_spec = self.__get_two_pane_one_pane_spec( ) elif layout == 'Filters, Image | Chart': filter_spec, image_spec, chart_spec = self.__get_two_pane_one_pane_spec( ) elif layout == 'Chart, Image | Filters': chart_spec, image_spec, filter_spec = self.__get_two_pane_one_pane_spec( ) elif layout == 'Image, Chart | Filters': image_spec, chart_spec, filter_spec = self.__get_two_pane_one_pane_spec( ) elif layout == 'Filters, Chart | Image': filter_spec, chart_spec, image_spec = self.__get_two_pane_one_pane_spec( ) elif layout == 'Chart, Filters | Image': chart_spec, filter_spec, image_spec = self.__get_two_pane_one_pane_spec( ) elif layout == "Chart | Filters": chart_spec, filter_spec = self.__get_two_pane_spec() elif layout == "Filters | Chart": filter_spec, chart_spec = self.__get_two_pane_spec() elif layout == "Chart | Image": chart_spec, image_spec = self.__get_two_pane_spec() elif layout == "Image | Chart": image_spec, chart_spec = self.__get_two_pane_spec() elif layout == "Pixel Perfect Image | Chart": gs = GridSpec(1, 1, wspace=self.widthSpacing.value(), hspace=self.heightSpacing.value()) chart_spec = gs.new_subplotspec((0, 0), 1, 1) self.__prepare_for_pixel_perfect() return image_spec, chart_spec, filter_spec