Пример #1
0
    def __init__(self, data_sets: list):

        # Verify user input
        num_dims = len(data_sets[0])
        # dimensions
        if num_dims < 2:
            raise ValueError('Must supply data with more than one dimension.')

        # Setup figure and axes
        x = range(num_dims)
        fig = mpl_figure.Figure()
        axes = list()
        for idx in range(num_dims - 1):
            axes.append(fig.add_subplot(1, num_dims - 1, idx + 1))

        # Store, initialize values
        self.fig = fig
        self._axes = axes
        self._ax_color_bar = None
        self._x = x
        self._data_sets = None
        self._data_sets_info = None
        self._num_dims = num_dims
        self._colors = None
        self._scores = None
        self._scores_norm_min = None
        self._scores_norm_max = None
        self._color_style = None
        self._color_map_norm = None
        self._use_variable_line_width = False
        self._sorted_scores_indices = None

        self._set_data(data_sets)
Пример #2
0
def plot_weight_posteriors(names, qm_vals, qs_vals, fname):
    """Save a PNG plot with histograms of weight means and stddevs.

  Args:
    names: A Python `iterable` of `str` variable names.
    qm_vals: A Python `iterable`, the same length as `names`,
      whose elements are Numpy `array`s, of any shape, containing
      posterior means of weight varibles.
    qs_vals: A Python `iterable`, the same length as `names`,
      whose elements are Numpy `array`s, of any shape, containing
      posterior standard deviations of weight varibles.
    fname: Python `str` filename to save the plot to.
  """
    fig = figure.Figure(figsize=(6, 3))
    canvas = backend_agg.FigureCanvasAgg(fig)

    ax = fig.add_subplot(1, 2, 1)
    for n, qm in zip(names, qm_vals):
        sns.distplot(qm.flatten(), ax=ax, label=n)
    ax.set_title("weight means")
    ax.set_xlim([-1.5, 1.5])
    ax.legend()

    ax = fig.add_subplot(1, 2, 2)
    for n, qs in zip(names, qs_vals):
        sns.distplot(qs.flatten(), ax=ax)
    ax.set_title("weight stddevs")
    ax.set_xlim([0, 1.])

    fig.tight_layout()
    canvas.print_figure(fname, format="png")
    print("saved {}".format(fname))
    def _setup_figure(self, img):
        """
        Args:
            Same as in :meth:`__init__()`.

        Returns:
            fig (matplotlib.pyplot.figure): top level container for all the image plot elements.
            ax (matplotlib.pyplot.Axes): contains figure elements and sets the coordinate system.
        """
        fig = mplfigure.Figure(frameon=False)
        self.dpi = fig.get_dpi()
        # add a small 1e-2 to avoid precision lost due to matplotlib's truncation
        # (https://github.com/matplotlib/matplotlib/issues/15363)
        fig.set_size_inches(
            (self.width * self.scale + 1e-2) / self.dpi,
            (self.height * self.scale + 1e-2) / self.dpi,
        )
        self.canvas = FigureCanvasAgg(fig)
        # self.canvas = mpl.backends.backend_cairo.FigureCanvasCairo(fig)
        ax = fig.add_axes([0.0, 0.0, 1.0, 1.0])
        ax.axis("off")
        ax.set_xlim(0.0, self.width)
        ax.set_ylim(self.height)

        self.fig = fig
        self.ax = ax
Пример #4
0
def plot_heldout_prediction(input_vals, probs, fname, n=10, title=""):
    """Save a PNG plot visualizing posterior uncertainty on heldout data.

  Args:
    input_vals: A `float`-like Numpy `array` of shape
      `[num_heldout] + IMAGE_SHAPE`, containing heldout input images.
    probs: A `float`-like Numpy array of shape `[num_monte_carlo,
      num_heldout, num_classes]` containing Monte Carlo samples of
      class probabilities for each heldout sample.
    fname: Python `str` filename to save the plot to.
    n: Python `int` number of datapoints to vizualize.
    title: Python `str` title for the plot.
  """
    fig = figure.Figure(figsize=(9, 3 * n))
    canvas = backend_agg.FigureCanvasAgg(fig)
    for i in range(n):
        ax = fig.add_subplot(n, 3, 3 * i + 1)
        ax.imshow(input_vals[i, :].reshape(IMAGE_SHAPE[:-1]),
                  interpolation="None")

        ax = fig.add_subplot(n, 3, 3 * i + 2)
        for prob_sample in probs:
            sns.barplot(np.arange(10), prob_sample[i, :], alpha=0.1, ax=ax)
            ax.set_ylim([0, 1])
        ax.set_title("posterior samples")

        ax = fig.add_subplot(n, 3, 3 * i + 3)
        sns.barplot(np.arange(10), np.mean(probs[:, i, :], axis=0), ax=ax)
        ax.set_ylim([0, 1])
        ax.set_title("predictive probs")
    fig.suptitle(title)
    fig.tight_layout()

    canvas.print_figure(fname, format="png")
    print("saved {}".format(fname))
Пример #5
0
def dt_plot(key, denominator_coords, denominator_data, numerator_coords,
            numerator_data):
    fig = figure.Figure(figsize=(4, 4 / golden_ratio))
    FigureCanvas(fig)
    axes = fig.add_axes((.14, .15, .98 - .14, .90 - .15))

    denominator_data = numpy.nan_to_num(denominator_data)
    numerator_data = numpy.nan_to_num(numerator_data)

    if numpy.any(denominator_data):
        axes.plot(denominator_coords,
                  denominator_data,
                  "k-",
                  label="Background")
    if numpy.any(numerator_data):
        axes.plot(numerator_coords, numerator_data, "r-", label="Injections")
    ymin, ymax = axes.get_ylim()
    axes.set_ylim((max(ymin, ymax - 14), ymax))
    axes.legend(loc="upper left")

    instrument1, instrument2 = key.split("-")[:2]
    axes.set_title(r"%s--%s Arrival Time Difference Distribution" %
                   (instrument1, instrument2))
    axes.set_ylabel(r"$\ln P$")
    axes.set_xlabel(r"$t_{\mathrm{%s}} - t_{\mathrm{%s}}$ (s)" %
                    (instrument1, instrument2))
    axes.xaxis.grid(True, which="major,minor")
    axes.yaxis.grid(True, which="major,minor")
    return fig
Пример #6
0
    def create_canvas_and_axes(self):
        # Create a figure.
        fig = figure.Figure()

        # Create a canvas and add the figure to it
        self.canvas = backend_agg.FigureCanvasAgg(fig)
        self.axes = fig.add_subplot(111)
Пример #7
0
def df_plot(key, denominator_coords, denominator_data, numerator_coords,
            numerator_data):
    fig = figure.Figure(figsize=(4, 4 / golden_ratio))
    FigureCanvas(fig)
    axes = fig.add_axes((.14, .15, .98 - .14, .90 - .15))

    denominator_data = numpy.nan_to_num(denominator_data)
    numerator_data = numpy.nan_to_num(numerator_data)

    if numpy.any(denominator_data):
        axes.plot(denominator_coords,
                  denominator_data,
                  "k-",
                  label="Background")
    if numpy.any(numerator_data):
        axes.plot(numerator_coords, numerator_data, "r-", label="Injections")
    ymin, ymax = axes.get_ylim()
    axes.set_ylim((max(ymin, ymax - 14), ymax))
    axes.legend(loc="upper left")

    instrument1, instrument2 = key.split("-")[:2]
    axes.set_title(r"%s--%s Frequency Cutoff Asymmetry Distribution" %
                   (instrument1, instrument2))
    axes.set_ylabel(r"$\ln P$")
    axes.set_xlabel(
        r"$\left({f_{\mathrm{cut}}}_{\mathrm{%s}} - {f_{\mathrm{cut}}}_{\mathrm{%s}}\right) / \frac{1}{2} \left({f_{\mathrm{cut}}}_{\mathrm{%s}} + {f_{\mathrm{cut}}}_{\mathrm{%s}}\right)$"
        % (instrument1, instrument2, instrument1, instrument2))
    axes.xaxis.grid(True, which="major,minor")
    axes.yaxis.grid(True, which="major,minor")
    return fig
Пример #8
0
def _make_ts_fig():
    fig = figure.Figure(figsize=(9, 9))
    ax1 = fig.add_subplot(2, 2, 1)
    ax2 = fig.add_subplot(2, 2, 2, sharex=ax1)
    ax3 = fig.add_subplot(2, 2, 3, sharex=ax1)
    ax4 = fig.add_subplot(2, 2, 4, sharex=ax1)
    return fig, [ax1, ax2, ax3, ax4]
Пример #9
0
def graphHeatMap(file_name, matrices, extents, names, axis_labels, title):
    '''current style only gens 2x2 heat maps! change length, width to make
    different kinds'''

    length = 2
    width = 2
    axes = []
    
    fig = figure.Figure(figsize = (15, 15))
    canvas = FigureCanvas(fig)
    fig.subplots_adjust(wspace = 0.45, hspace = 0.45)
    fig.suptitle(title)
    
    for matrix, extent, name, ind, axis_label in zip(matrices, extents, names, range(len(matrices)), axis_labels):
#         ax = plt.subplot2grid((width, length), (ind // 2, ind % 2))
        ax = fig.add_subplot(width, length, ind + 1)
        ax.set_title(name, fontsize=24)
        ax.set_xlabel(axis_label[0], fontsize=24)
        ax.set_ylabel(axis_label[1], fontsize=24)
        img = ax.imshow(matrix, extent = extent, interpolation = 'none', vmin = np.nanmin(matrix), vmax = np.nanmax(matrix), cmap='bwr')
        ax.tick_params(axis='both', which='both', labelsize=18)
        fig.colorbar(img)
    
    
    pdf = PdfPages(file_name)
    pdf.savefig(fig)
    pdf.close()
Пример #10
0
def plot_setup(*args):
    # reduce scale of codeclimate complaints
    fig = figure.Figure()
    FigureCanvas(fig)
    ax = fig.gca()
    ax.grid(True)
    return fig, ax
Пример #11
0
 def GetFigure(self, figsize=(6,6), dpi=75, 
               facecolor="1.0", edgecolor="1.0", linewidth="1.0",
               frameon=True, subplotpars=None):
   fig = figure.Figure(figsize=figsize, dpi=dpi, facecolor=facecolor,
                       edgecolor=edgecolor, linewidth=linewidth,
                       frameon=frameon, subplotpars=subplotpars)
   backend_agg.FigureCanvasAgg(fig)
   return fig
Пример #12
0
def test_no_pyplot():
    # tests pickle-ability of a figure not created with pyplot
    from matplotlib.backends.backend_pdf import FigureCanvasPdf
    fig = mfigure.Figure()
    _ = FigureCanvasPdf(fig)
    ax = fig.add_subplot(1, 1, 1)
    ax.plot([1, 2, 3], [1, 2, 3])
    pickle.dump(fig, BytesIO(), pickle.HIGHEST_PROTOCOL)
Пример #13
0
def test_axes_object_with_ax():
    fig = figure.Figure()
    ax = fig.add_subplot(1, 1, 1)
    fig1, ax1 = validate.axes_object(ax)
    assert isinstance(ax1, axes.Axes)
    assert isinstance(fig1, figure.Figure)
    assert ax1 is ax
    assert fig1 is fig
Пример #14
0
def test_unpickle_canvas():
    fig = mfigure.Figure()
    assert fig.canvas is not None
    out = BytesIO()
    pickle.dump(fig, out)
    out.seek(0)
    fig2 = pickle.load(out)
    assert fig2.canvas is not None
Пример #15
0
def plot2d(orig: Tensor,
           recons: Tensor,
           model_name: str,
           epoch: int,
           out_path: str,
           rows: int,
           cols: int,
           display: str = 'horizontal',
           scaling: float = 1.0,
           dpi: int = 400,
           title: str = None,
           suptitle: dict = {},
           img_filter: str = None,
           imshow_args: dict = {}):
    fig = figure.Figure(figsize=(cols * scaling, rows * scaling), dpi=dpi)
    grid = ImageGrid(
        fig,
        111,  # similar to subplot(111)
        nrows_ncols=(rows, cols),  # creates 2x2 grid of axes
        axes_pad=0.1)  # pad between axes in inch.
    i = 0
    n = min(rows * cols, orig.shape[0])
    to_pil = ToPILImage()
    displays = {
        'horizontal': -1,
        'vertical': -2,
    }
    dim = displays[display]
    for _ in range(rows):
        done = False
        for _ in range(cols):
            if i >= n:
                done = True
                break
            o = orig[i]
            r = recons[i]
            if img_filter is not None:
                o = run_img_filter(o, img_filter)
                r = run_img_filter(r, img_filter)
            img = torch.cat([o, r], dim=dim).byte()
            #img = img.numpy()
            #img = np.transpose(img, axes=(2, 0, 1))
            #img = img.astype(np.byte)
            #img = Image.frombytes(img)
            img = to_pil(img)
            ax = grid[i]
            ax.axis('off')
            ax.imshow(img, **imshow_args)
            i += 1
        if done:
            break
    if title is not None:
        interpolated = plot_title(title, model_name, epoch)
        fig.suptitle(interpolated, **suptitle)
    fig.tight_layout()
    fig.savefig(out_path + '.png', bbox_inches='tight')
    plt.close(fig)
    plt.close('all')
    def plot_estimated_variogram(self,
                                 clims: Optional[Tuple[float, float]] = None):
        # Visualize estimated variogram function and display figure on screen
        nx, ny, nz = self._nonparest.variogram_map_values().shape
        dx, dy, dz = self._nonparest.grid_resolution()

        xmin = -int(nx / 2)
        xmax = -xmin
        ymin = -int(ny / 2)
        ymax = -ymin
        zmin = -int(nz / 2)
        zmax = -zmin

        xv = np.linspace(xmin, xmax, nx)
        yv = np.linspace(ymin, ymax, ny)
        zv = np.linspace(zmin, zmax, nz)
        xm, ym, zm = np.meshgrid(xv, yv, zv)

        z_plot = int(np.floor(nz * 0.5))
        vfunc = AnisotropicVariogram(
            family=self._family, nug=self._nugget).get_variogram_function()
        indep_data = np.vstack((xm.ravel(), ym.ravel(), zm.ravel()))
        params = list(self._parameters.values())

        if not np.any(np.isnan(params)):
            varest = vfunc(indep_data, *params)
            varest = np.reshape(varest, (ny, nx, nz))
        else:
            varest = np.full(shape=(ny, nx, nz), fill_value=np.nan)

        fig = mpl_f.Figure()
        ax1, ax2 = fig.subplots(1, 2)
        # Setup axis 1
        if clims is not None:
            img = ax1.imshow(varest[:, :, z_plot],
                             extent=(dx * xmin, dx * xmax, dy * ymin,
                                     dy * ymax),
                             vmin=clims[0],
                             vmax=clims[1])
        else:
            img = ax1.imshow(varest[:, :, z_plot],
                             extent=(dx * xmin, dx * xmax, dy * ymin,
                                     dy * ymax))
        ax1.set_xlabel("h_x")
        ax1.set_ylabel("h_y")
        ax1.set_title("Fitted variogram model")
        fig.colorbar(img, ax=ax1, orientation='horizontal')
        # Setup axis 2
        sill = vfunc(np.full((3, 1), np.inf), *params)
        img2 = ax2.imshow(varest[:, :, z_plot] / sill,
                          vmax=1.0,
                          vmin=0.0,
                          extent=(dx * xmin, dx * xmax, dy * ymin, dy * ymax))
        ax2.set_xlabel("h_x")
        ax2.set_ylabel("h_y")
        ax2.set_title("Fitted variogram model (scaled)")
        fig.colorbar(img2, ax=ax2, orientation='horizontal')
        return fig
Пример #17
0
def _plot_images(
    image_dir: PurePath,
    orig: str,
    image_list: List,
    scores: bool = False,
    outfile: str = None,
) -> None:
    """
    Plotting function for plot_duplicates() defined below.

    Args:
        image_dir: image directory where all files in duplicate_map are present.
        orig: filename for which duplicates are to be plotted.
        image_list: List of duplicate filenames, could also be with scores (filename, score).
        scores: Whether only filenames are present in the image_list or scores as well.
        outfile:  Name of the file to save the plot.
    """
    n_ims = len(image_list)
    ncols = 4  # fixed for a consistent layout
    nrows = int(np.ceil(n_ims / ncols)) + 1
    fig = figure.Figure(figsize=(10, 14))

    gs = gridspec.GridSpec(nrows=nrows, ncols=ncols)
    ax = plt.subplot(
        gs[0, 1:3])  # Always plot the original image in the middle of top row
    ax.imshow(
        cv2.cvtColor(cv2.imread(str(image_dir / orig), cv2.IMREAD_COLOR),
                     cv2.COLOR_BGR2RGB))
    ax.set_title('Original Image: {}'.format(orig))
    ax.axis('off')

    for i in range(0, n_ims):
        row_num = (i // ncols) + 1
        col_num = i % ncols

        ax = plt.subplot(gs[row_num, col_num])
        if scores:
            ax.imshow(
                cv2.cvtColor(
                    cv2.imread(str(image_dir / image_list[i][0]),
                               cv2.IMREAD_COLOR), cv2.COLOR_BGR2RGB))
            val = _formatter(image_list[i][1])
            title = ' '.join([image_list[i][0], f'({val})'])
        else:
            ax.imshow(
                cv2.cvtColor(
                    cv2.imread(str(image_dir / image_list[i]),
                               cv2.IMREAD_COLOR), cv2.COLOR_BGR2RGB))
            title = image_list[i]

        ax.set_title(title, fontsize=6)
        ax.axis('off')
    gs.tight_layout(fig)

    if outfile:
        plt.savefig(outfile)

    plt.show()
Пример #18
0
def showGraph():
    """
    Creates a window that shows a popularity graph.
    """
    from booklist import monthly

    # Creating a window
    statsWin = Tk()
    statsWin.title("Book Popularity")
    statsWin.geometry("1024x768")
    statsWin.resizable(False, False)

    # Creating the graph
    graphFrame = Frame(statsWin)
    fig = plt.Figure(figsize=(10.24, 7.68), dpi=100, tight_layout=True)
    area = fig.add_subplot(111)

    statsWin.withdraw()  # Hides window until done

    # translating options into respective values (days)
    optn = timeVar.get()
    tRange = {
        "Last Month": 30,
        "Last 3 Months": 90,
        "Last 6 Months": 180,
        "Last Year": 365,
    }

    # gets all transactions from log that is within selected time frame
    bookList = monthly(tRange[optn])

    x = list(bookList.keys())
    y = list(bookList.values())

    if len(x) < 5 or len(y) < 5:
        messagebox.showwarning(
            "Feature Unavailable.",
            "This feature is not available as the log file is not populated enough."
        )
        return

    # Embeds graph into Tk
    graph = FigureCanvasTkAgg(fig, graphFrame)

    # Plotting graph
    area.bar(x, y)
    area.set_xlabel("Book Titles")
    area.set_ylabel("Copies on loan")

    # rotates label 90 degrees for readability
    [label.set_rotation(90) for label in area.get_xticklabels()]

    graph.draw()
    graph.get_tk_widget().pack()
    graphFrame.pack()

    statsWin.deiconify()  # show window
    statsWin.mainloop()
Пример #19
0
def makePortionFigure(deblend, origMimg, origMimgB, pedestal=0.0):

    portions = []
    centers = []
    boxes = []
    for i, peak in enumerate(deblend.peaks):
        # make an image matching the size of the original
        portionedImg = afwImage.ImageF(origMimg.getBBox())

        # get the heavy footprint for the flux aportioned to this peak
        heavyFoot = peak.getFluxPortion()
        footBox = heavyFoot.getBBox()
        pk = peak.peak
        centers.append((pk.getIx(), pk.getIy()))
        boxes.append(((footBox.getMinX(), footBox.getMinY()), footBox.getWidth(), footBox.getHeight()))
        print(i, peak, pk.getIx(), pk.getIy(), footBox, "skip:", peak.skip)

        # make a sub-image for this peak, and put the aportioned flux into it
        portionedSubImg = afwImage.ImageF(portionedImg, footBox)
        portionedSubImg += pedestal
        heavyFoot.insert(portionedSubImg)

        portions.append(portionedImg)

    fig = figure.Figure(figsize=(8, 10))
    canvas = FigCanvas(fig)

    g = int(numpy.ceil(numpy.sqrt(len(deblend.peaks))))
    gx, gy = g, g+1

    def makeAx(ax, im, title):
        im = im.getArray()
        a = ax.imshow(im, cmap='gray')
        cb = fig.colorbar(a)
        ax.set_title(title, size='small')
        ax.set_xlim((0, im.shape[0]))
        ax.set_ylim((0, im.shape[1]))
        for t in ax.get_xticklabels() + ax.get_yticklabels() + cb.ax.get_yticklabels():
            t.set_size('x-small')
        return ax

    # show the originals
    makeAx(fig.add_subplot(gy, gx, 1), origMimg.getImage(), "Orig")
    makeAx(fig.add_subplot(gy, gx, 2), origMimgB.getImage(), "Missing Src")

    # show each aportioned image
    i = gy
    for i_p in range(len(portions)):
        im = portions[i_p]
        ax = makeAx(fig.add_subplot(gy, gx, i), im, "")
        xy, w, h = boxes[i_p]
        ax.add_patch(Rectangle(xy, w, h, fill=False, edgecolor='#ff0000'))
        for x, y in centers:
            ax.plot(x, y, '+', color='#00ff00')
        i += 1

    return fig
Пример #20
0
    def __init__(self):
        self.fig = mpl_figure.Figure()
        self.ax = self.fig.add_subplot(111)

        mpl_backend_qt5agg.FigureCanvasQTAgg.__init__(self, self.fig)
        mpl_backend_qt5agg.FigureCanvasQTAgg.setSizePolicy(
            self, QtWidgets.QSizePolicy.Expanding,
            QtWidgets.QSizePolicy.Expanding)
        mpl_backend_qt5agg.FigureCanvasQTAgg.updateGeometry(self)
    def createThreeDFigure(self):

        self.figure = figure.Figure(dpi=80)
        figCanvas = FigureCanvas(self.figure)

        layout = QVBoxLayout(self)
        layout.addWidget(figCanvas)  # 添加FigureCanvas对象
        layout.setContentsMargins(0, 0, 0, 0)
        layout.setSpacing(0)
Пример #22
0
    def __init__(self,
                 name=None,
                 figsize=(6, 4),
                 position=(0.1, 0.1, 0.8, 0.8)):
        import matplotlib.backends.backend_tkagg as mpTkAgg
        import matplotlib.figure as mpfig
        import sys

        # Window widget
        self.window = Tk.Toplevel()
        if name is not None:
            assert type(name) is str
            self.window.title(name)
        self.name = self.window.title()

        def callback():
            self.window.withdraw()

        self.window.bind("<Destroy>", callback)
        self.window.protocol("WM_DELETE_WINDOW", callback)

        button = Tk.Button(ROOT,
                           text='Show %s window' % self.window.title(),
                           command=self.window.deiconify)
        button.pack(side=Tk.TOP)
        button.pack(fill=Tk.BOTH, expand=1)

        # Instantiate figure and plot
        self.f = mpfig.Figure(figsize=figsize, dpi=100)
        self.ax = self.f.add_subplot(111)
        self.ax.set_position(position)

        # Instantiate canvas
        self.canvas = canvas = mpTkAgg.FigureCanvasTkAgg(self.f, self.window)

        # Pack canvas into window
        canvas.get_tk_widget().pack(side=Tk.TOP, fill=Tk.BOTH, expand=1)
        canvas._tkcanvas.pack(side=Tk.TOP, fill=Tk.BOTH, expand=1)

        # Instantiate and pack toolbar
        self.toolbar = toolbar = mpTkAgg.NavigationToolbar2TkAgg(
            canvas, self.window)

        # Instantiate and pack quit button
        #self.button = button = Tk.Button(self.window, text='Quit', command=sys.exit)
        #button.pack(side=Tk.BOTTOM)

        # Show canvas and toolbar
        toolbar.update()
        canvas.show()

        # Init nplots to zero
        self.nplots = 0

        # Init names
        self.names = []
        return
Пример #23
0
    def __init__(self, width, height, dpi=96):
        # time increments, by minute
        self.time_inc_min = 15

        # create matplotlib figure
        self.fig = figure.Figure(figsize=(width, height), dpi=dpi)

        # colors used for successive points
        self.colors = ['r', 'b', 'g', 'c', 'm', 'y']
Пример #24
0
def rain_clock(dataframe, raincol='precip'):
    """ Mathematically dubious representation of the likelihood of rain at
    at any hour given that will rain.

    Parameters
    ----------
    dataframe : pandas.DataFrame
    raincol : string, optional (default = 'precip')
        The name of the column in *dataframe* that contains the
        rainfall series.

    Returns
    -------
    fig : matplotlib.Figure

    """

    if not hasattr(dataframe, raincol):
        raise ValueError('input `dataframe` must have a `%s` column' % raincol)

    rainfall = dataframe[raincol]
    am_hours = numpy.arange(0, 12)
    am_hours[0] = 12
    rainhours = rainfall.index.hour
    rain_by_hour = []
    for hr in numpy.arange(24):
        selector = (rainhours == hr)
        total_depth = rainfall[selector].sum()
        num_obervations = rainfall[selector].count()
        rain_by_hour.append(total_depth / num_obervations)

    bar_width = 2 * numpy.pi / 12 * 0.8

    fig = figure.Figure(figsize=(7, 3))
    ax1 = fig.add_subplot(1, 2, 1, polar=True)
    ax2 = fig.add_subplot(1, 2, 2, polar=True)
    theta = numpy.arange(0.0, 2 * numpy.pi, 2 * numpy.pi / 12)
    ax1.bar(theta + 2 * numpy.pi / 12 * 0.1,
            rain_by_hour[:12],
            bar_width,
            color='DodgerBlue',
            linewidth=0.5)
    ax2.bar(theta + 2 * numpy.pi / 12 * 0.1,
            rain_by_hour[12:],
            bar_width,
            color='Crimson',
            linewidth=0.5)
    ax1.set_title('AM Hours')
    ax2.set_title('PM Hours')
    for ax in [ax1, ax2]:
        ax.set_theta_zero_location("N")
        ax.set_theta_direction('clockwise')
        ax.set_xticks(theta)
        ax.set_xticklabels(am_hours)
        ax.set_yticklabels([])

    return fig
Пример #25
0
def main():

    args = parse_args()

    fixed_img = skio.imread(args.fixed_img, as_gray=True)
    fixed_annot = np.loadtxt(args.fixed_annot,
                             delimiter=',',
                             skiprows=1,
                             dtype=np.int32)

    moved_img = skio.imread(args.moved_img, as_gray=True)
    moved_annot = np.loadtxt(args.moved_annot,
                             delimiter=',',
                             skiprows=1,
                             dtype=np.int32)

    # load map data
    mapdata = get_map_from_h5(args.map, args.map_group)
    nodes_x, nodes_y = get_nodes_from_h5(args.map, args.map_group)

    # update csv points from interpolated map
    interp_x = si.RegularGridInterpolator((nodes_x, nodes_y), mapdata[0])
    interp_y = si.RegularGridInterpolator((nodes_x, nodes_y), mapdata[1])

    offsets_x = interp_x(fixed_annot[:, 1:])
    offsets_y = interp_y(fixed_annot[:, 1:])

    # Set figsize for 1:1 pixels
    figsize = (fixed_img.shape[1] / dpi, fixed_img.shape[0] / dpi)

    fig = mf.Figure(figsize=figsize)
    canvas = mplbea.FigureCanvasAgg(fig)
    ax = fig.add_axes((0, 0, 1, 1))
    ax.set_axis_off()
    ax.imshow(fixed_img, cmap=cols1[0], aspect='auto')
    ax.imshow(moved_img, cmap=cols2[0], alpha=0.5, aspect='auto')
    ax.plot(fixed_annot[:, 1],
            fixed_annot[:, 2],
            color=cols1[1],
            marker='.',
            linestyle="none",
            markersize="1")
    ax.plot(moved_annot[:, 1],
            moved_annot[:, 2],
            color=cols2[1],
            marker='.',
            linestyle="none",
            markersize="1")

    ax.quiver(fixed_annot[:, 1],
              fixed_annot[:, 2],
              offsets_x,
              offsets_y,
              angles='xy',
              scale_units='xy',
              scale=1)
    fig.savefig(args.output, dpi=dpi)
Пример #26
0
 def plot_spectrogram(self):
     f = fig.Figure()
     f.add_subplot(111).specgram(self.wav_data,
                                 NFFT=1024,
                                 noverlap=900,
                                 Fs=self.sr)
     canvas = FigureCanvasTkAgg(f, master=self)
     canvas.draw()
     canvas.get_tk_widget().pack(side=tk.TOP, fill=tk.BOTH, expand=1)
Пример #27
0
def coordPlot(exposure, finder, pngfile):

    mm = finder._mm
    cmm = finder._mmCals
    img = exposure.getMaskedImage().getImage().getArray()
    bins = 1.0*img.shape[1]/mm.img.shape[1]
    xx, yy = np.meshgrid(np.arange(mm.img.shape[1], dtype=int), np.arange(mm.img.shape[0], dtype=int))
    x = (bins*xx[finder._isCandidate]).astype(int)
    y = (bins*yy[finder._isCandidate]).astype(int)

    cimg = np.zeros(img.shape)
    cimg[y,x] = 1.0


    def small(ax):
        for t in ax.get_xticklabels() + ax.get_yticklabels():
            t.set_size("small")
            
    fig = figure.Figure(figsize=(8.0,4.0))
    fig.subplots_adjust(bottom=0.15)
    can = FigCanvas(fig)
    
    ax = fig.add_subplot(1, 3, 1)
    ax.imshow(np.arcsinh(img), origin='lower', cmap='gray')
    ax.set_xlim([0, img.shape[1]])
    ax.set_ylim([0, img.shape[0]])
    small(ax)
    
    ax = fig.add_subplot(1, 3, 3)
    stride = 1
    #ax.plot(mm.theta[::stride], mm.ellip[::stride], '.k', ms=0.2, alpha=0.2)
    ax.scatter(mm.theta[::stride], mm.ellip[::stride],
               c=np.clip(mm.center[::stride], 0.0, 4.0*finder.centerLimit),
               s=0.2, alpha=0.2, edgecolor='none')
    if len(cmm) == 2:
        i = 0
    else:
        i = 2
    ax.hlines([cmm[i].ellip], -np.pi/2.0, np.pi/2.0, color='k', linestyle='-')
    ax.set_xlim([-np.pi/2.0, np.pi/2.0])
    ax.set_ylim([0.0, 1.0])
    ax.set_xlabel("$\\theta$")
    ax.set_ylabel("$e=1-B/A$")
    ax.yaxis.set_label_position("right")
    ax.yaxis.tick_right()
    small(ax)
    
    ax = fig.add_subplot(1, 3, 2)
    ax.imshow(cimg, origin='lower', cmap='gray_r')
    ax.plot(x, y, 'k.', ms=1.0)
    ax.set_xlim([0, img.shape[1]])
    ax.set_ylim([0, img.shape[0]])
    small(ax)
    
    fig.savefig(pngfile)
    fig.savefig(re.sub("png", "eps", pngfile))
Пример #28
0
 def __init__(self, name="holder occupation"):
     """Create a new instance of this graph"""
     self.name = name
     self.__fig = figure.Figure()
     self.__fig.hold(False)
     self.plot = self.__fig.add_subplot(111)
     self.lines = []
     self.labels = []
     self.legend = dict()
     self.max = 0
Пример #29
0
 def __init__(self, name=_("product life-cycle"), limit=50):
     """Create a new instance of a ProductChart"""
     self.name = name
     self.limit = limit
     self.__fig = figure.Figure()
     self.plot = self.__fig.add_subplot(111)
     self.rows = []
     self.legend = dict()
     self.colormap = cm.ScalarMappable(cmap=cm.gist_rainbow)
     self.colormap.set_clim(0, 1)
Пример #30
0
 def __init__(self):
     self._fig: figure.Figure = figure.Figure(frameon=False, dpi=100.0)
     self._figure_canvas: backend_qt5agg.FigureCanvasQTAgg = backend_qt5agg.FigureCanvasQTAgg(self._fig)
     # Space around axes. Documentation not helpful. Taken from stack-overflow.
     self._fig.subplots_adjust(top=1, bottom=0, right=1, left=0, hspace=0, wspace=0)
     self._ax: figure.Axes = self._fig.subplots()
     self._drawable: Optional[drawable.Drawable] = None
     self._buf: Optional[memoryview] = None
     self._rgba_output: Optional[np.ndarray] = None
     self._current_shape: Optional[tuples.ImageShape] = None