def plot_with_overlay(img, probas_, fig: plt.Figure = None, figsize=None, **kwargs): if fig is None: fig: plt.Figure = plt.figure(figsize=figsize) ax = fig.add_subplot(1, 3, 1) ax.imshow(img) ax.set_title("Initial image") ax.axis('off') ax = fig.add_subplot(1, 3, 2) ax.imshow(probas_) ax.set_title("Proba map") ax.axis('off') ax = fig.add_subplot(1, 3, 3) ax.imshow(img, extent=[0, 1, 0, 1]) prob_overlay = make_overlay(probas_) ax.imshow(prob_overlay, extent=[0, 1, 0, 1]) ax.set_title("Overlay") ax.axis('off') fig.tight_layout()
def _default_after_plots(self, fig: plt.Figure): """Set properties after charts creation Args: fig: matplotlib Figure """ fig.tight_layout() if self.figpath is not None: fig.savefig(self.figpath.format(i=self.file_idx)) self.file_idx += 1 plt.show()
def save_plot( path: str, name: str, fig: plt.Figure, file_formats: Iterable[str] = ("png", "pdf"), timestamp: Optional[dt.datetime] = None, ) -> Generator: """ Context manager that creates a new figure on entry and saves the figure using the specified name, format, and path on exit. Parameters ---------- path : str Path prefix to use in constructing the result path name : str Basename to use in constructing the result path file_formats : iterable of str File extensions with which to save the result. Elements must be accepted by ``plt.savefig`` timestamp : datetime or None, optional If given, draw a watermark with the timestamp at the bottom of the figure Examples -------- >>> fig = plt.plot(np.cos(np.linspace(-np.pi, np.pi))) >>> fig.title("My cool plot") >>> save_plot('example/plots', 'test_plot', fig, 'png'): """ outfiles = [ os.path.join(path, os.extsep.join([name, file_format])) for file_format in file_formats ] if timestamp is not None: fig.tight_layout(rect=(0, 0.05, 1, 1)) # leave space for timestamp _plot_updated_timestamp(timestamp, fig) else: fig.tight_layout() # Make sure the directory exists os.makedirs(path, exist_ok=True) for outfile in outfiles: fig.savefig( outfile, transparent=True, ) plt.close(fig=fig)
def set_figtext(fig: plt.Figure, text: str): """Replaces current figtext with new text""" fig = plt.figure( fig.number) # Just to set as current figure to add text to for i, t in enumerate( fig.texts): # Remove any fig text that has been added previously if t.get_position() == _fig_text_position: t.remove() plt.figtext(_fig_text_position[0], _fig_text_position[1], text, horizontalalignment='center', wrap=True) fig.tight_layout(rect=[0, 0.1, 1, 0.98]) # rect=(left, bottom, right, top)
def npsPlotByKey(pkg: NotePkg, fig:plt.Figure = None, shape: Tuple = None, window=1000, stride=None, title=True, legend=True, barKwargs=None) -> plt.Figure: """ This creates an NPS Plot with the axes. :param pkg: Any Note Package :param fig: The figure to plot on, if None, we use gcf() :param shape: The shape of the axes to take. (rows, columns) :param window: The window of the roll :param stride: The stride length of the roll :param title: Whether to show the key titles :param legend: Whether to show legend. False to show none, True to show on first, 'all' to show on all :param barKwargs: The kwargs to pass into plot() """ if fig is None: fig = plt.gcf() if barKwargs is None: barKwargs = {} keys = pkg.maxColumn() + 1 # This gives us the keys if shape is None: rows = keys cols = 1 shape = (rows, cols) else: assert shape[0] * shape[1] >= keys, "Shape must be able to hold all keys." ax: np.ndarray = fig.subplots(nrows=shape[0], ncols=shape[1], sharex='all', sharey='all') ax = ax.flatten() for key in range(keys): if legend == 'all': npsPlot(pkg.inColumns([key]), ax=ax[key], window=window, stride=stride, legend=True, barKwargs=barKwargs) elif legend is True and key == 0: npsPlot(pkg.inColumns([key]), ax=ax[key], window=window, stride=stride, legend=True, barKwargs=barKwargs) else: npsPlot(pkg.inColumns([key]), ax=ax[key], window=window, stride=stride, legend=False, barKwargs=barKwargs) ax: List[plt.Axes] if title: ax[key].set_title(f"Key: {key}") fig.tight_layout() return fig
def add_figure(self, fig: plt.Figure, caption: str, width: str = r"\textwidth"): """Adds a pyplot figure to the document Arguments: fig: pyplot figure handle caption: caption to add to the figure in the document width: the width of the image, by default this is set to the pagewidth """ figfn = self.docdir / "{}.png".format(self.figidx) fig.tight_layout() fig.savefig(figfn, dpi=120) self.figidx += 1 figtex = figtemplate.format(fn=figfn.name, caption=caption, width=width) self.add_body(figtex)
def _( figure: Figure, scale: str = "down", inherit_font: bool = True, tight_layout: bool = True, bbox_inches: str = None, ) -> SVGContentConfiguration: if tight_layout: figure.tight_layout() fig_size = figure.get_size_inches() with io.StringIO() as str_io: figure.savefig(str_io, format="svg", transparent=True, bbox_inches=bbox_inches) svg = str_io.getvalue() return SVGContentConfiguration( data=clean_svg( svg, scale=scale, width=fig_size[0], height=fig_size[1], inherit_font=inherit_font, ) )
def save(fig: plt.Figure, name: str): figure_dir = get_figure_dir() fig.tight_layout() fig.savefig(os.path.join(figure_dir, name + ".pgf")) fig.savefig(os.path.join(figure_dir, name + ".pdf"))
def add_figure(self, name: str, fig: plt.Figure) -> None: fig.tight_layout() self.figures[name] = fig
def save_figure(self, key, fig: plt.Figure): fig.tight_layout() fig.savefig(self._to_path(key, 'png'), dpi=120) plt.close(fig)
def save(fig: plt.Figure, name: str): cur_dir = os.path.dirname(os.path.realpath(__file__)) figure_dir = os.path.join(cur_dir, "report", "figures") fig.tight_layout() fig.savefig(os.path.join(figure_dir, name + ".pgf")) fig.savefig(os.path.join(figure_dir, name + ".pdf"))
class MainWindow(QMainWindow, Ui_MainWindow): def __init__(self, *args, **kwargs): super(MainWindow, self).__init__(*args, **kwargs) self.setupUi(self) self.setWindowTitle('vmon') # initialize menu bar to enable data export and import self.menu = MenuBarPanel(self) self.open_btn.clicked.connect(self.open_image) self.clear_btn.clicked.connect(self.clear_screen) self.plot_cb.currentTextChanged.connect(self.reconfigure_axes) self.interpolate_cb.currentTextChanged.connect(self.reconfigure_axes) self.legend_chb.stateChanged.connect(self.reconfigure_axes) self.peaks_chb.stateChanged.connect(self.reconfigure_axes) def open_image(self): formats = "sheets (*.csv *.xlsx)" self.sheet_files = qtw.QFileDialog.getOpenFileNames( self, 'Open Sheets', '.', formats) self.reconfigure_axes() def clear_screen(self): # clear screen if hasattr(self, "fig"): del self.fig if hasattr(self, "canvas"): del self.canvas if hasattr(self, "ax"): self.ax.clear() del self.ax if hasattr(self, "toolbar"): self.screen.removeWidget(self.toolbar) self.toolbar.close() del self.toolbar if hasattr(self, "image"): self.screen.removeWidget(self.image) self.image.close() del self.image def get_rx_spectrum(self, file_name, interpolation="Cubic Spline"): # Resolution of IMon 512 USB is 0.166015625 nm = 166.015 pm x = np.arange(1510, 1595, 0.166015625, dtype=float) dx = np.arange(1510, 1595, 0.001000000, dtype=float) # load data into data frame df = pd.read_csv(file_name, sep="\t") df = df[[f"Pixel {i}" for i in range(1, 513)]] # calculate mean of all the entries and reverse it mean = df.mean().values[::-1] if interpolation == "Cubic Spline": # perform cublic spline interpolation cs = interpolate.CubicSpline(x, mean) dy = cs(dx) elif interpolation == "Linear": # perform cublic spline interpolation cs = interpolate.CubicSpline(x, mean) dy = cs(dx) else: pass return dx, dy def reconfigure_axes(self): if not hasattr(self, "fig"): self.fig = Figure() if not hasattr(self, "canvas"): self.canvas = FigureCanvas(self.fig) if not hasattr(self, "ax"): self.ax = self.fig.add_subplot(111) self.ax.clear() else: self.ax.clear() self.files = [] self.peaks = [] for sheet_file in self.sheet_files[0]: dx, dy = self.get_rx_spectrum( sheet_file, interpolation=self.interpolate_cb.currentText()) self.files.append(sheet_file.split('/')[-1].split('.')[0][-4:]) self.peaks.append(dx[dy.argmax()]) plot = self.plot_cb.currentText() if plot == "Normalised": dy = dy / max(dy) elif plot == "Desibles": dy = 20 * np.log(dy / max(dy)) if self.legend_chb.isChecked(): if self.peaks_chb.isChecked(): self.ax.plot( dx, dy, label= f"{sheet_file.split('/')[-1]},{dx[dy.argmax()]:.3f}") else: self.ax.plot(dx, dy, label=f"{sheet_file.split('/')[-1]}") else: self.ax.plot(dx, dy) # self.ax.scatter(dx[ymaxp], dy[ymaxp],label = 'peak L:' + )) if self.plot_cb.currentText() == "Raw": self.ax.set_title("FBG Spectrums") self.ax.set_ylabel("Amplitude (AU)") self.ax.set_xlabel("Wavelength (nm)") self.ax.set_xlim(1511, 1594) if self.legend_chb.isChecked(): self.ax.legend() if self.plot_cb.currentText() == "Normalised": self.ax.set_title("Normalised FBG Spectrums") self.ax.set_ylabel("Normalised Amplitude (AU)") self.ax.set_xlabel("Wavelength (nm)") self.ax.set_xlim(1511, 1594) if self.legend_chb.isChecked(): self.ax.legend() if self.plot_cb.currentText() == "Peaks": self.ax.clear() self.ax.set_title("Peaks in FBG Spectrums") self.ax.set_ylabel("Peak Wavelength (nm)") self.ax.set_xlabel("Files") self.ax.plot(np.arange(len(self.peaks)), self.peaks) self.ax.plot(self.files, self.peaks) if self.plot_cb.currentText() == "Desibels": self.ax.set_title("FBG Spectrums in Desibels") self.ax.set_ylabel("Amplitude (dB)") self.ax.set_xlabel("Wavelength (nm)") self.ax.set_xlim(1511, 1594) if self.legend_chb.isChecked(): self.ax.legend() self.ax.grid("True") # self.fig.subplots_adjust(top=0.921, # bottom=0.123, # left=0.169, # right=0.972, # hspace=0.2, # wspace=0.2 # ) self.fig.tight_layout() if not hasattr(self, "image"): self.image = FigureCanvas(self.fig) self.screen.addWidget(self.image) if not hasattr(self, "toolbar"): self.toolbar = NavigationToolbar(self.image, self.display, coordinates=True) self.screen.addWidget(self.toolbar) self.fig.canvas.draw() self.statusbar.showMessage("Reconfigured Plot")
def set_figure_properties(fig: plt.Figure, **kwargs) -> None: """ Ease the configuration of a :class:`matplotlib.figure.Figure`. Parameters ---------- fig : matplotlib.figure.Figure The figure. Keyword arguments ----------------- fontsize : int Font size to use for the plot titles, and axes ticks and labels. Defaults to 12. tight_layout : bool `True` to fit the whole subplots into the figure area, `False` otherwise. Defaults to `True`. tight_layout_rect : Sequence[float] A rectangle (left, bottom, right, top) in the normalized figure coordinate that the whole subplots area (including labels) will fit into. Defaults to (0, 0, 1, 1). suptitle : str The figure title. Defaults to an empty string. xlabel : str TODO ylabel : str TODO figlegend_on : bool TODO figlegend_ax : int TODO figlegend_loc : `str` or `Tuple[float, float]` TODO figlegend_framealpha : float TODO figlegend_ncol : int TODO subplots_adjust_hspace : float TODO subplots_adjust_vspace : float TODO """ fontsize = kwargs.get("fontsize", 12) tight_layout = kwargs.get("tight_layout", True) tight_layout_rect = kwargs.get("tight_layout_rect", (0, 0, 1, 1)) suptitle = kwargs.get("suptitle", "") x_label = kwargs.get("x_label", "") x_labelpad = kwargs.get("x_labelpad", 20) y_label = kwargs.get("y_label", "") y_labelpad = kwargs.get("y_labelpad", 20) figlegend_on = kwargs.get("figlegend_on", False) figlegend_ax = kwargs.get("figlegend_ax", 0) figlegend_loc = kwargs.get("figlegend_loc", "lower center") figlegend_framealpha = kwargs.get("figlegend_framealpha", 1.0) figlegend_ncol = kwargs.get("figlegend_ncol", 1) wspace = kwargs.get("subplots_adjust_wspace", None) hspace = kwargs.get("subplots_adjust_hspace", None) rcParams["font.size"] = fontsize if suptitle is not None and suptitle != "": fig.suptitle(suptitle, fontsize=fontsize + 1) if x_label != "" or y_label != "": ax = fig.add_subplot(111) ax.set_frame_on(False) ax.set_xticks([]) ax.set_xticklabels([], visible=False) ax.set_yticks([]) ax.set_yticklabels([], visible=False) if x_label != "": ax.set_xlabel(x_label, labelpad=x_labelpad) if y_label != "": ax.set_ylabel(y_label, labelpad=y_labelpad) if tight_layout: fig.tight_layout(rect=tight_layout_rect) if figlegend_on: handles, labels = fig.get_axes()[figlegend_ax].get_legend_handles_labels() fig.legend( handles, labels, loc=figlegend_loc, framealpha=figlegend_framealpha, ncol=figlegend_ncol, ) if wspace is not None: fig.subplots_adjust(wspace=wspace) if hspace is not None: fig.subplots_adjust(hspace=hspace)
def save_fig(fig: plt.Figure, name: str, size: Tuple[int, int] = [3.5, 2]): fig.tight_layout() fig.set_size_inches(w=size[0], h=size[1]) fig.savefig(os.path.join(figure_dir(), name + ".pgf")) fig.savefig(os.path.join(figure_dir(), name + ".pdf"))
# add loader icon frames = [PhotoImage(file='./image/loader.gif', format='gif -index %i' % i) for i in range(8)] loader = Label(root) is_loader = False # create new figure figure = Figure() is_redraw = False # for before median filter graph_1 = figure.add_subplot(311) graph_1.set_ylabel('Frequency (Hz)') graph_1.set_xlabel('Time') graph_1.set_ylim(0, 400) scatter_1 = None figure.tight_layout() # for after median filter graph_2 = figure.add_subplot(312) graph_2.set_ylabel('Frequency (Hz)') graph_2.set_xlabel('Time') graph_2.set_ylim(0, 400) scatter_2 = None figure.tight_layout() # for wave file graph_3 = figure.add_subplot(313) graph_3.set_title('No wave file') graph_3.set_ylabel('Amplitude') graph_3.set_xlabel('Time') plot_3 = None