我们从Python开源项目中,提取了以下38个代码示例,用于说明如何使用matplotlib.pyplot.Figure()。
def embedCollectionsBuilder(self): self.dpi = 100 self.fig = plt.Figure() self.canvas = FigureCanvas(self.fig) self.ax = self.fig.add_subplot(111) # self.ax.set_axis_bgcolor("white") # when a button is pressed on the canvas? self.canvas.mpl_connect('button_press_event', self.onCollectionsClick) #self.canvas.mpl_connect('button_release_event', self.onCollectionsClick) self.canvas.mpl_connect('pick_event', self.onCollectionsPick) mpl_toolbar = NavigationToolbar(self.canvas, self.main_build_frame) self.gridLayout.addWidget(self.canvas) self.gridLayout.addWidget(mpl_toolbar) self.fig.subplots_adjust( left=0.0, right=1, top=1, bottom=0, wspace=0.02, hspace=0.04) self.dragged = None
def test_bpt(self, maps, useoi): if maps.bptsums is None: pytest.skip('no bpt data found in galaxy test data') bptflag = 'nooi' if useoi is False else 'global' masks, figure, axes = maps.get_bpt(show_plot=False, return_figure=True, use_oi=useoi) assert isinstance(figure, plt.Figure) for mech in self.mechanisms: assert mech in masks.keys() assert np.sum(masks[mech]['global']) == maps.bptsums[bptflag][mech] if useoi: assert len(axes) == 4 else: assert len(axes) == 3 for ax in axes: assert isinstance(ax, LocatableAxes)
def plot_dist( main_file, mask_file, xlabel, distribution=None, xlabel2=None, figsize=DINA4_LANDSCAPE): data = _get_values_inside_a_mask(main_file, mask_file) fig = plt.Figure(figsize=figsize) FigureCanvas(fig) gsp = GridSpec(2, 1) ax = fig.add_subplot(gsp[0, 0]) sns.distplot(data.astype(np.double), kde=False, bins=100, ax=ax) ax.set_xlabel(xlabel) ax = fig.add_subplot(gsp[1, 0]) sns.distplot(np.array(distribution).astype(np.double), ax=ax) cur_val = np.median(data) label = "{0!g}".format(cur_val) plot_vline(cur_val, label, ax=ax) ax.set_xlabel(xlabel2) return fig
def _render(fig, showlegend=None): """Plot a matploltib or plotly figure""" if isinstance(fig, plt.Figure): fig = plotly.tools.mpl_to_plotly(fig, **PLOTLY_TO_MPL_KWS) if showlegend is not None: fig.layout['showlegend'] = showlegend if not IN_NOTEBOOK: message = 'Lens explorer can only plot in a Jupyter notebook' logger.error(message) raise ValueError(message) else: if not py.offline.__PLOTLY_OFFLINE_INITIALIZED: py.init_notebook_mode() return py.iplot(fig, **PLOTLY_KWS)
def __init__(self, main_window, locs): super().__init__() self.main_window = main_window self.locs = locs self.figure = plt.Figure() self.canvas = FigureCanvasQTAgg(self.figure) self.plot() vbox = QtGui.QVBoxLayout() self.setLayout(vbox) vbox.addWidget(self.canvas) vbox.addWidget((NavigationToolbar2QT(self.canvas, self))) self.setWindowTitle('Picasso: Filter') this_directory = os.path.dirname(os.path.realpath(__file__)) icon_path = os.path.join(this_directory, 'icons', 'filter.ico') icon = QtGui.QIcon(icon_path) self.setWindowIcon(icon)
def plot(self, **kwargs): """Plot current quadtree :param axes: Axes instance to plot in, defaults to None :type axes: [:py:class:`matplotlib.Axes`], optional :param figure: Figure instance to plot in, defaults to None :type figure: [:py:class:`matplotlib.Figure`], optional :param **kwargs: kwargs are passed into `plt.imshow` :type **kwargs: dict """ self._initImagePlot(**kwargs) self.data = self._quadtree.leaf_matrix_means self.title = 'Quadtree Means' self._addInfoText() if self._show_plt: plt.show()
def scatter(x,y,xlabel='x',ylabel='y',title=None,line=False,name=None,show=False): sns.set() title = "%s vs %s"%(xlabel,ylabel) if title is None else title plt.scatter(x,y) if line: plt.plot(x,y) plt.title(title) plt.ylabel('y: %s'%ylabel) plt.xlabel('x: %s'%xlabel) if name is not None: #fig = plt.Figure() plt.savefig(name) if show: plt.show() plt.clf()
def compare(self, sim_data, plot=False, fig=None): """Compares the results of a simulation to this these data Performs the following actions 1. Calculates the time shift required to align the simulation data with the experiment 2. Evaluates the simulation data at the experimental time-stamps 3. Calculates the difference between the simulation and the experiment for every experimental time step. Experiment **less** simulation Args: sim_data(list): The output from a call to a F_UNCLE Experiment Keyword Args: plot(bool): Flag to plot the comparison fig(plt.Figure): If not none, the figure object on which to plot Return: (np.ndarray): The difference between sim_data and this experiment at each experimental time-stamp """ tau = sim_data[2]['tau'] epsilon = self.data[1][self.window]\ - sim_data[2]['mean_fn'](self.data[0][self.window] - tau) return epsilon
def latticeplot(optic, diagnostics, size=None): ymin, ymax = 0, 100 fig = Figure(frameon=False) if size is not None: fig.set_figwidth(size[0]) fig.set_figheight(size[1]) ax = fig.add_subplot(111) drawlattice(ax, optic, diagnostics, [ymin, ymax], .3, checkconf=False) s = cumsum(optic[1, :]) ax.set_xlim(0, s[-1]) ax.set_ylim(ymin, ymax) ax.axis('off') ax.get_xaxis().set_visible(False) ax.get_yaxis().set_visible(False) return fig
def _get_axes(kwargs, use_3d=False, use_polar=False): """Prepare the axis to draw into. Parameters ---------- use_3d: bool If yes, an axis with 3D projection is created. use_polar: bool If yes, the plot will have polar coordinates. Kwargs ------ ax: Optional[plt.Axes] An already existing axis to be used. figsize: Optional[tuple] Size of the new figure (if no axis is given). Returns ------ fig : plt.Figure ax : plt.Axes | Axes3D """ figsize = kwargs.pop("figsize", default_figsize) if "ax" in kwargs: ax = kwargs.pop("ax") fig = ax.get_figure() elif use_3d: fig = plt.figure(figsize=figsize) ax = fig.add_subplot(111, projection='3d') elif use_polar: fig = plt.figure(figsize=figsize) ax = fig.add_subplot(111, projection='polar') else: fig, ax = plt.subplots(figsize=figsize) return fig, ax
def initFeatureCanvas(self): self.featureFig = plt.Figure() ##self.featureFig.subplots_adjust(hspace=0.32, wspace=0.02, ## left=0.065, right=0.95, top=0.97, bottom=0.18) self.featureAx = self.featureFig.add_subplot(1,1,1) self.featureCanvas = FigureCanvas(parent=self, id=wx.ID_ANY, figure=self.featureFig)
def initCanvas(self): """Initialize a new matplotlib canvas, figure and axis. """ self.plotPanel = wx.Panel(self) self.plotPanel.SetBackgroundColour('white') plotSizer = wx.BoxSizer(orient=wx.VERTICAL) self.plotPanel.SetSizer(plotSizer) self.fig = plt.Figure(facecolor='white') #self.canvas = FigureCanvas(parent=self, id=wx.ID_ANY, figure=self.fig) self.canvas = FigureCanvas(parent=self.plotPanel, id=wx.ID_ANY, figure=self.fig) self.ax = self.fig.add_subplot(1,1,1) self.ax.set_xlabel('Time (s)') self.ax.set_ylabel('Frequency (Hz)') self.cbAx = self.fig.add_axes([0.91, 0.05, 0.03, 0.93]) #self.fig.subplots_adjust(hspace=0.0, wspace=0.0, # left=0.035, right=0.92, top=0.98, bottom=0.05) self.adjustMargins() self.firstPlot() self.lastSize = (0,0) self.needsResizePlot = True self.canvas.Bind(wx.EVT_SIZE, self.resizePlot) self.canvas.Bind(wx.EVT_IDLE, self.idleResizePlot) ##self.plotToolbar = widgets.PyPlotNavbar(self.canvas) ##plotSizer.Add(self.plotToolbar, proportion=0, flag=wx.EXPAND) plotSizer.Add(self.canvas, proportion=1, flag=wx.EXPAND) #self.plotToolbar.Hide()
def initERPCanvas(self): #self.erpFig = plt.Figure() #self.erpAx = self.erpFig.add_subplot(1,1,1) #self.erpCanvas = FigureCanvas(parent=self, id=wx.ID_ANY, figure=self.erpFig) self.erpFig = plt.Figure() self.erpFig.subplots_adjust(hspace=0.32, wspace=0.02, left=0.065, right=0.95, top=0.97, bottom=0.18) gs = pltgs.GridSpec(2,4) self.erpAx = self.erpFig.add_subplot(gs[0,:]) self.h1Ax = self.erpFig.add_subplot(gs[1,0]) self.h2Ax = self.erpFig.add_subplot(gs[1,1]) self.h3Ax = self.erpFig.add_subplot(gs[1,2]) self.h4Ax = self.erpFig.add_subplot(gs[1,3]) self.cbAx = self.erpFig.add_axes([0.05, 0.08, 0.9, 0.05]) self.erpCanvas = FigureCanvas(parent=self, id=wx.ID_ANY, figure=self.erpFig)
def initERPCanvas(self): self.erpFig = plt.Figure() self.erpFig.subplots_adjust(hspace=0.32, wspace=0.02, left=0.065, right=0.95, top=0.97, bottom=0.18) gs = pltgs.GridSpec(2,4) self.erpAx = self.erpFig.add_subplot(gs[0,:]) self.h1Ax = self.erpFig.add_subplot(gs[1,0]) self.h2Ax = self.erpFig.add_subplot(gs[1,1]) self.h3Ax = self.erpFig.add_subplot(gs[1,2]) self.h4Ax = self.erpFig.add_subplot(gs[1,3]) self.cbAx = self.erpFig.add_axes([0.05, 0.08, 0.9, 0.05]) self.erpCanvas = FigureCanvas(parent=self, id=wx.ID_ANY, figure=self.erpFig)
def initResponse(self): self.freqResponseFig = plt.Figure() self.freqResponseCanvas = FigureCanvas(parent=self, id=wx.ID_ANY, figure=self.freqResponseFig) self.freqResponseAx = self.freqResponseFig.add_subplot(1,1,1) #self.freqResponseFig.tight_layout() self.phaseResponseFig = plt.Figure() self.phaseResponseCanvas = FigureCanvas(parent=self, id=wx.ID_ANY, figure=self.phaseResponseFig) self.phaseResponseAx = self.phaseResponseFig.add_subplot(1,1,1) #self.freqResponseFig.tight_layout() responseSizer = wx.BoxSizer(wx.VERTICAL) freqResponseControlBox = widgets.ControlBox(self, label='Freqency Response', orient=wx.VERTICAL) freqResponseControlBox.Add(self.freqResponseCanvas, proportion=1, flag=wx.ALL | wx.EXPAND, border=8) responseSizer.Add(freqResponseControlBox, proportion=1, flag=wx.TOP | wx.RIGHT | wx.BOTTOM | wx.EXPAND, border=10) phaseResponseControlBox = widgets.ControlBox(self, label='Phase Response', orient=wx.VERTICAL) phaseResponseControlBox.Add(self.phaseResponseCanvas, proportion=1, flag=wx.ALL | wx.EXPAND, border=8) responseSizer.Add(phaseResponseControlBox, proportion=1, flag=wx.RIGHT | wx.BOTTOM | wx.EXPAND, border=10) self.bottomSizer.Add(responseSizer, proportion=1, flag=wx.EXPAND) self.freqResponseCanvas.SetMinSize((0,0)) self.phaseResponseCanvas.SetMinSize((0,0)) # could we prevent resize when panel is not visible? XXX - idfah self.freqResponseLastSize = (0,0) self.freqResponseCanvas.Bind(wx.EVT_SIZE, self.freqResponseResize) self.phaseResponseLastSize = (0,0) self.phaseResponseCanvas.Bind(wx.EVT_SIZE, self.phaseResponseResize) self.updateResponse()
def test_bpt_diffsn(self, maps): if maps.bptsums is None: pytest.skip('no bpt data found in galaxy test data') masks, figure, __ = maps.get_bpt(show_plot=False, return_figure=True, use_oi=True, snr_min=5) assert isinstance(figure, plt.Figure) for mech in self.mechanisms: assert mech in masks.keys() assert np.sum(masks[mech]['global']) == maps.bptsums['snrmin5'][mech]
def test_bind_to_figure(self, plateifu, mpl): maps = Maps(plateifu=plateifu, release=mpl) __, __, axes = maps.get_bpt(show_plot=False, return_figure=True) assert len(axes) == 4 for ax in axes: new_fig = ax.bind_to_figure() assert isinstance(new_fig, plt.Figure) assert new_fig.axes[0].get_ylabel() != ''
def plot_fd(fd_file, fd_radius, mean_fd_dist=None, figsize=DINA4_LANDSCAPE): fd_power = _calc_fd(fd_file, fd_radius) fig = plt.Figure(figsize=figsize) FigureCanvas(fig) if mean_fd_dist: grid = GridSpec(2, 4) else: grid = GridSpec(1, 2, width_ratios=[3, 1]) grid.update(hspace=1.0, right=0.95, left=0.1, bottom=0.2) ax = fig.add_subplot(grid[0, :-1]) ax.plot(fd_power) ax.set_xlim((0, len(fd_power))) ax.set_ylabel("Frame Displacement [mm]") ax.set_xlabel("Frame number") ylim = ax.get_ylim() ax = fig.add_subplot(grid[0, -1]) sns.distplot(fd_power, vertical=True, ax=ax) ax.set_ylim(ylim) if mean_fd_dist: ax = fig.add_subplot(grid[1, :]) sns.distplot(mean_fd_dist, ax=ax) ax.set_xlabel("Mean Frame Displacement (over all subjects) [mm]") mean_fd = fd_power.mean() label = r'$\overline{{\text{{FD}}}}$ = {0:g}'.format(mean_fd) plot_vline(mean_fd, label, ax=ax) return fig
def __init__(self, info_dialog): super().__init__() self.setWindowTitle('Pick Histograms') this_directory = os.path.dirname(os.path.realpath(__file__)) icon_path = os.path.join(this_directory, 'icons', 'render.ico') icon = QtGui.QIcon(icon_path) self.setWindowIcon(icon) self.resize(1000, 400) self.figure = plt.Figure() self.canvas = FigureCanvasQTAgg(self.figure) vbox = QtGui.QVBoxLayout() self.setLayout(vbox) vbox.addWidget(self.canvas) vbox.addWidget((NavigationToolbar2QT(self.canvas, self)))
def setCanvas(self, **kwargs): """Set canvas to plot in :param figure: Matplotlib figure to plot in :type figure: :py:class:`matplotlib.Figure` :param axes: Matplotlib axes to plot in :type axes: :py:class:`matplotlib.Axes` :raises: TypeError """ axes = kwargs.get('axes', None) figure = kwargs.get('figure', None) if isinstance(axes, plt.Axes): self.fig, self.ax = axes.get_figure(), axes self._show_plt = False elif isinstance(figure, plt.Figure): self.fig, self.ax = figure, figure.gca() self._show_plt = False elif axes is None and figure is None and self.fig is None: self.fig, self.ax = plt.subplots(1, 1) self._show_plt = True else: raise TypeError('axes has to be of type matplotlib.Axes. ' 'figure has to be of type matplotlib.Figure') self.image = AxesImage(self.ax) self.ax.add_artist(self.image)
def _initImagePlot(self, **kwargs): """ Initiate the plot :param figure: Matplotlib figure to plot in :type figure: :py:class:`matplotlib.Figure` :param axes: Matplotlib axes to plot in :type axes: :py:class:`matplotlib.Axes` """ self.setCanvas(**kwargs) self.setColormap(kwargs.get('cmap', 'RdBu')) self.colormapAdjust() self.ax.set_xlim((0, self._scene.frame.E.size)) self.ax.set_ylim((0, self._scene.frame.N.size)) self.ax.set_aspect('equal') self.ax.invert_yaxis() self.ax.set_title(self.title) def close_figure(ev): self.fig = None self.ax = None try: self.fig.canvas.mpl_connect('close_event', close_figure) # specify! except: pass
def plot(self, **kwargs): """Placeholder in prototype class :param figure: Matplotlib figure to plot in :type figure: :py:class:`matplotlib.Figure` :param axes: Matplotlib axes to plot in :type axes: :py:class:`matplotlib.Axes` :param **kwargs: kwargs are passed into `plt.imshow` :type **kwargs: dict :raises: NotImplemented """ raise NotImplemented self._initImagePlot(**kwargs) if self._show_plt: plt.show()
def plot(self, component='displacement', **kwargs): """Plots any component fom Scene The following components are recognizes - 'cartesian.dE' - 'cartesian.dN' - 'cartesian.dU' - 'displacement' - 'phi' - 'theta' :param **kwargs: Keyword args forwarded to `matplotlib.plt.imshow()` :type **kwargs: {dict} :param component: Component to plot ['cartesian.dE', 'cartesian.dN', 'cartesian.dU', 'displacement', 'phi', 'theta'] :type component: {string}, optional :param axes: Axes instance to plot in, defaults to None :type axes: :py:class:`matplotlib.Axes`, optional :param figure: Figure instance to plot in, defaults to None :type figure: :py:class:`matplotlib.Figure`, optional :param **kwargs: kwargs are passed into `plt.imshow` :type **kwargs: dict :returns: Imshow instance :rtype: :py:class:`matplotlib.image.AxesImage` :raises: AttributeError """ self._initImagePlot(**kwargs) self.component = component self.title = self.components_available[component] if self._show_plt: plt.show()
def plot(): from matplotlib import pyplot as plt fig = plt.Figure() ax5 = fig.add_subplot(411) ax5.plot(UPDATE_HISTORY[0:N, 1]) ax5.set_xlabel('Time step') ax5.set_ylabel('Reward') ax5.set_title('Reward over time') ax6 = fig.add_subplot(412) ax6.plot(AVG_REWARD[0:N]) ax6.set_xlabel('Time step') ax6.set_ylabel('Average reward') ax6.set_title('Average reward over time') ax7 = fig.add_subplot(413) ax7.plot(EXPERIMENT.nfq._q_predicted[0:N], 'o') ax7.set_ylim([-2, 8]) ax7.set_xlabel('Time step') ax7.set_ylabel('Predicted Q-value for chosen action') ax7.set_title('Predicted Q-value over time') ax8 = fig.add_subplot(414) ax8.plot(EXPERIMENT.nfq._loss_history[0:EXPERIMENT.nfq.k], 'o') ax8.set_ylim([-3, 3]) ax8.set_xlabel('Episode') ax8.set_ylabel('NFQ loss') ax8.set_title('NFQ loss over time') fig.set_size_inches(16, 16) fig.tight_layout() canvas = FigureCanvas(fig) png_output = StringIO.StringIO() canvas.print_png(png_output) response = make_response(png_output.getvalue()) response.headers['Content-Type'] = 'image/png' return response
def setupUI(self): self.setGeometry(600, 200, 1200, 600) self.setWindowTitle("PyChart Viewer v0.1") self.setWindowIcon(QIcon('icon.png')) self.lineEdit = QLineEdit() self.pushButton = QPushButton("?????") self.pushButton.clicked.connect(self.pushButtonClicked) self.fig = plt.Figure() self.canvas = FigureCanvas(self.fig) leftLayout = QVBoxLayout() leftLayout.addWidget(self.canvas) # Right Layout rightLayout = QVBoxLayout() rightLayout.addWidget(self.lineEdit) rightLayout.addWidget(self.pushButton) rightLayout.addStretch(1) layout = QHBoxLayout() layout.addLayout(leftLayout) layout.addLayout(rightLayout) layout.setStretchFactor(leftLayout, 1) layout.setStretchFactor(rightLayout, 0) self.setLayout(layout)
def plot_basis(self, axes=None, fig=None, labels=[], linstyles=[]): """Plots the basis function and their first and second derivatives Args: fig(plt.Figure): A valid figure object on which to plot axes(plt.Axes): A valid axes, *Ignored* labels(list): The labels, *Ignored* linestyles(list): The linestyles, *Ignored* Return: (plt.Figure): The figure """ if fig is None: fig = plt.figure() else: fig = fig # end dof_init = copy.deepcopy(self.get_dof()) basis = [] dbasis = [] ddbasis = [] v_list = np.linspace(self.get_option('spline_min'), self.get_option('spline_max'), 300) for i, coeff in enumerate(dof_init): new_dof = np.zeros(dof_init.shape[0]) new_dof[i] = 1.0 # coeff tmp_spline = self.update_dof(new_dof) basis.append(tmp_spline(v_list)) dbasis.append(tmp_spline.derivative(n=1)(v_list)) ddbasis.append(tmp_spline.derivative(n=2)(v_list)) # end basis = np.array(basis) dbasis = np.array(dbasis) ddbasis = np.array(ddbasis) ax1 = fig.add_subplot(311) ax2 = fig.add_subplot(312) ax3 = fig.add_subplot(313) knots = tmp_spline.get_t() for i in range(basis.shape[0]): ax1.plot(v_list, basis[i, :], label='dof{:02d}'.format(i)) ax1.plot(knots, np.zeros(knots.shape), 'xk') ax2.plot(v_list, dbasis[i, :]) ax2.plot(knots, np.zeros(knots.shape), 'xk') ax3.plot(v_list, ddbasis[i, :]) ax3.plot(knots, np.zeros(knots.shape), 'xk') ax1.legend(loc='best') return fig
def plot_fisher_data(self, fisher_data, axes=None, fig=None, linestyles=[], labels=[]): """ Args: fisher_dat(tuple): Data from the fisher_decomposition function *see docscring for definition* Keyword Args: axes(plt.Axes): *Ignored* fig(plt.Figure): A valid figure to plot on linestyles(list): A list of valid linestyles *Ignored* labels(list): A list of labels *Ignored* """ if fig is None: fig = plt.Figure() else: pass # end ax1 = plt.subplot(211) ax2 = plt.subplot(212) eigs = fisher_data[0] eig_vects = fisher_data[1] eig_func = fisher_data[2] indep = fisher_data[3] # ax1.bar(np.arange(eigs.shape[0]), eigs, width=0.9, color='black', # edgecolor='none', orientation='vertical') ax1.semilogy(eigs, 'sk') ax1.set_xlabel("Eigenvalue number") ax1.set_ylabel(r"Eigenvalue / Pa$^{-2}$") ax1.set_xlim(-0.5, len(eigs) - 0.5) ax1.set_ylim([0.1 * min(eigs[np.nonzero(eigs)]), 10 * max(eigs)]) ax1.xaxis.set_major_locator(MultipleLocator(1)) ax1.xaxis.set_major_formatter(FormatStrFormatter('%d')) styles = ['-g', '-.b', '--m', ':k', '-c', '-.y', '--r'] *\ int(math.ceil(eig_func.shape[0] / 7.0)) for i in range(eig_func.shape[0]): ax2.plot(indep, eig_func[i], styles[i], label="{:d}".format(i)) # end ax2.legend(loc='best') ax2.get_legend().set_title("Eigen-\nfunctions", prop={'size': 7}) ax2.set_xlabel(r"Specific volume / cm$^3$ g$^{-1}$") ax2.set_ylabel("Eigenfunction response / Pa") fig.tight_layout() return fig
def plot(self, data, axes=None, fig=None, linestyles=['-k'], labels=[]): """Plots the object Args: data(tuple): The output from a call to a Sphere object Keyword Args: axes(plt.Axes): The axes on which to plot *Ignored* fig(plt.Figure): The figure on which to plot linestyles(list): Strings for the linestyles labels(list): Strings for the labels Return: (plt.Figure): A reference to the figure containing the plot """ if fig is None: fig = plt.figure() else: pass # end ax1 = fig.add_subplot(321) ax2 = fig.add_subplot(322) ax3 = fig.add_subplot(323) ax4 = fig.add_subplot(324) ax5 = fig.add_subplot(325) ax6 = fig.add_subplot(326) ax1.plot(data[0], data[1][1], linestyles[0]) ax1.set_xlabel('Time from detonation / s') ax1.set_ylabel('Radius of sphere / cm') ax2.plot(data[0], data[1][0]) ax2.set_ylabel(r'Velocity of sphere / cm s$^{-1}$') ax3.plot(data[0], data[1][3]) ax3.set_ylabel(r'Specific volume / cm$^{3}$ g$^{-1}$') ax4.plot(data[0], data[1][4]) ax4.plot(data[0], np.array(data[1][5]) * 1E3, '-k') ax4.set_ylabel(r'Pressure / Pa') ax5.plot(data[0], data[1][2]) ax5.set_ylabel(r'Thickness / cm') ax6.plot(data[0], data[1][6]) ax6.set_ylabel(r'Strain in material / cm cm$^{-1}$') return fig
def plot_sens_matrix(sens_matrix, simid, models, mkey, fig=None): """Prints the sensitivity matrix Args: sens_matrix(dict): Dictionary of sensitivity matrices simid(str): Key for simulation models(OrderedDict): Ordered dictionary of models mkey(str): Key in models corresponding to the EOSModel Keyword Args fig(plt.Figure): A valid matplotlib figure on which to plot. If `None`, creates a new figure Return: (plt.Figure): The figure """ if simid not in sens_matrix: raise IndexError('simid not in the sensitivity' 'matrix dictionary') if mkey not in models: raise IndexError('mkey not in the models' ' dictionary') if fig is None: fig = plt.figure() else: fig = fig # end ax = fig.gca() model = models[mkey] idx = 0 for key in models: shape = models[key].shape() if key == mkey: break else: idx += shape # end # end model_sens = sens_matrix[simid][:, idx: idx + shape] for j in range(shape): ax.plot(model_sens[:, j], label='{:02d}'.format(j)) # end ax.set_ylabel('Sensitivity') ax.set_xlabel('Model resp. indep. var.') ax.legend(bbox_to_anchor=(1.05, 1), loc=2, borderaxespad=0.) ax.get_legend().set_title("DOF") return fig
def bind_to_figure(ax, fig=None): """Copies axes to a new figure. This is a custom implementation of a method to copy axes from one matplotlib figure to another. Matplotlib does not allow this, so we create a new figure and copy the relevant lines and containers. This is all quite hacky and may stop working in future versions of matplotlib, but it seems to be the only way to bind axes from one figure to a different one. Current limitations include: 1) the legend is copied but its style is not maintained; 2) scatter plots do not maintain the marker type, markers are always replaced with squares. """ if fig is not None: assert isinstance(fig, plt.Figure), 'argument must be a Figure' assert len(fig.axes) == 1, 'figure must have one and only one axes' new_ax = fig.axes[0] else: fig, new_ax = plt.subplots() new_ax.set_facecolor(ax.get_facecolor()) for line in ax.lines: data = line.get_data() new_ax.plot(data[0], data[1], linestyle=line.get_linestyle(), color=line.get_color(), zorder=line.zorder, label=line.get_label()) for collection in ax.collections: data = collection.get_offsets() new_ax.scatter(data[:, 0], data[:, 1], marker='s', facecolor=collection.get_facecolors(), edgecolor=collection.get_edgecolors(), s=collection.get_sizes(), zorder=line.zorder, label=collection.get_label()) for text in ax.texts: xx, yy = text.get_position() new_ax.text(xx, yy, text.get_text(), family=text.get_fontfamily(), fontsize=text.get_fontsize(), color=text.get_color(), ha=text.get_horizontalalignment(), va=text.get_verticalalignment(), zorder=text.zorder) for image in ax.images: new_ax.imshow(image.get_array(), interpolation=image.get_interpolation()) if ax.legend_: new_ax.legend() new_ax.grid(ax.get_xgridlines(), color=ax.get_xgridlines()[0].get_color(), alpha=ax.get_xgridlines()[0].get_alpha()) new_ax.grid(ax.get_ygridlines(), color=ax.get_xgridlines()[0].get_color(), alpha=ax.get_xgridlines()[0].get_alpha()) new_ax.set_xlim(ax.get_xlim()) new_ax.set_ylim(ax.get_ylim()) new_ax.set_xlabel(ax.get_xlabel()) new_ax.set_ylabel(ax.get_ylabel()) return fig
def plot_pairdensity_mpl(ls, column1, column2): """Plot the pairwise density between two columns. This plot is an approximation of a scatterplot through a 2D Kernel Density Estimate for two numerical variables. When one of the variables is categorical, a 1D KDE for each of the categories is shown, normalised to the total number of non-null observations. For two categorical variables, the plot produced is a heatmap representation of the contingency table. Parameters ---------- ls : :class:`~lens.Summary` Lens `Summary`. column1 : str First column. column2 : str Second column. Returns ------- :class:`plt.Figure` Matplotlib figure containing the pairwise density plot. """ pair_details = ls.pair_details(column1, column2) pairdensity = pair_details['pairdensity'] x = np.array(pairdensity['x']) y = np.array(pairdensity['y']) Z = np.array(pairdensity['density']) fig, ax = plt.subplots() if ls.summary(column1)['desc'] == 'categorical': idx = np.argsort(x) x = x[idx] Z = Z[:, idx] # Create labels and positions for categorical axis x_labels = dict(enumerate(x)) _set_integer_tick_labels(ax.xaxis, x_labels) x = np.arange(-0.5, len(x), 1.0) if ls.summary(column2)['desc'] == 'categorical': idx = np.argsort(y) y = y[idx] Z = Z[idx] y_labels = dict(enumerate(y)) _set_integer_tick_labels(ax.yaxis, y_labels) y = np.arange(-0.5, len(y), 1.0) X, Y = np.meshgrid(x, y) ax.pcolormesh(X, Y, Z, cmap=DEFAULT_COLORSCALE.lower()) ax.set_xlabel(column1) ax.set_ylabel(column2) ax.set_title(r'$\it{{ {} }}$ vs $\it{{ {} }}$'.format(column1, column2)) return fig
def plot_correlation_mpl(ls, include=None, exclude=None): """Plot the correlation matrix for numeric columns Plot a Spearman rank order correlation coefficient matrix showing the correlation between columns. The matrix is reordered to group together columns that have a higher correlation coefficient. The columns to be plotted in the correlation plot can be selected through either the ``include`` or ``exclude`` keyword arguments. Only one of them can be given. Parameters ---------- ls : :class:`~lens.Summary` Lens `Summary`. include : list of str List of columns to include in the correlation plot. exclude : list of str List of columns to exclude from the correlation plot. Returns ------- :class:`plt.Figure` Matplotlib figure containing the pairwise density plot. """ columns, correlation_matrix = ls.correlation_matrix(include, exclude) num_cols = len(columns) if num_cols > 10: annotate = False else: annotate = True fig, ax = plt.subplots() sns.heatmap(correlation_matrix, annot=annotate, fmt='.2f', ax=ax, xticklabels=columns, yticklabels=columns, vmin=-1, vmax=1, cmap='RdBu_r', square=True) ax.xaxis.tick_top() # Enforces a width of 2.5 inches per cell in the plot, # unless this exceeds 10 inches. width_inches = len(columns) * 2.5 while width_inches > 10: width_inches = 10 fig.set_size_inches(width_inches, width_inches) return fig
def plot_pairdensity(ls, column1, column2): """Plot the pairwise density between two columns. This plot is an approximation of a scatterplot through a 2D Kernel Density Estimate for two numerical variables. When one of the variables is categorical, a 1D KDE for each of the categories is shown, normalised to the total number of non-null observations. For two categorical variables, the plot produced is a heatmap representation of the contingency table. Parameters ---------- ls : :class:`~lens.Summary` Lens `Summary`. column1 : str First column. column2 : str Second column. Returns ------- :class:`plotly.Figure` Plotly figure containing the pairwise density plot. """ pair_details = ls.pair_details(column1, column2) pairdensity = pair_details['pairdensity'] x = np.array(pairdensity['x']) y = np.array(pairdensity['y']) Z = np.array(pairdensity['density']) if ls.summary(column1)['desc'] == 'categorical': idx = np.argsort(x) x = x[idx] Z = Z[:, idx] if ls.summary(column2)['desc'] == 'categorical': idx = np.argsort(y) y = y[idx] Z = Z[idx] data = [go.Heatmap(z=Z, x=x, y=y, colorscale=DEFAULT_COLORSCALE)] layout = go.Layout( title='<i>{}</i> vs <i>{}</i>'.format(column1, column2)) layout['xaxis'] = { 'type': pairdensity['x_scale'], 'autorange': True, 'title': column1 } layout['yaxis'] = { 'type': pairdensity['y_scale'], 'autorange': True, 'title': column2 } fig = go.Figure(data=data, layout=layout) fig.data[0]['showscale'] = False return fig
def plot(self, fig=None, fscale='log', print_width=False): """ Plots the impulse response and the transfer function of the filter. """ # validate figure if fig is None: fig_passed = False fig, axes = plt.subplots(nrows=2) else: fig_passed = True if not isinstance(fig, plt.Figure): raise TypeError('fig must be matplotlib Figure, got {}' ' instead.'.format(type(fig))) # test if is figure and has 2 axes n_axes = len(fig.axes) if n_axes < 2: raise ValueError('Passed figure must have at least two axes' ', given figure has {}.'.format(n_axes)) axes = fig.axes # compute periodogram fft_length = max(int(2 ** np.ceil(np.log2(self.fir.shape[0]))), 1024) s = Spectrum(fft_length=fft_length, block_length=self.fir.size, step=None, fs=self.fs, wfunc=np.ones, donorm=False) s.periodogram(self.fir) s.plot('Transfer function of FIR filter "Carrier"', fscale=fscale, axes=axes[0]) # print the frequency and the bandwidth if print_width: freq = np.linspace(0, s.fs / 2, s.fft_length // 2 + 1) psd = s.psd[0][0, :] psd = 10.0 * np.log10(np.maximum(psd, 1.0e-12)) i0 = np.argmax(psd) over_3db = np.nonzero(psd > psd[i0] - 3)[0] f_low = freq[over_3db[0]] f_high = freq[over_3db[-1]] df = f_high - f_low f0 = freq[i0] print('f0 = %.3f Hz, df_3db = %.3f Hz [%.3f, %.3f], df/f = %.3f' % (f0, df, f_low, f_high, df / f0)) # plots axes[1].plot(self.fir) if self.extract_complex: axes[1].plot(self.fir_imag) axes[1].set_title('Impulse response of FIR filter "Carrier"') axes[1].set_xlabel('Samples') axes[1].set_ylabel('Amplitude') if not fig_passed: fig.tight_layout() return fig