Ejemplo n.º 1
0
def _generate_histogram(m):
  # Make a 350px by 32px image for a slider background
  fig = Figure(figsize=(3.5,0.32), dpi=100, tight_layout=False)
  # This is required, even though we don't explicitly use the canvas.
  canvas = FigureCanvasAgg(fig)
  ax = fig.add_subplot(1,1,1)
  vrange = float(m.bounds[1] - m.bounds[0])
  num_bins = np.ceil(vrange / m.step) + 1
  if np.isnan(num_bins):
    ax.hist(m.arr)
  elif num_bins > 300:
    ax.hist(m.arr, 300, range=m.bounds)
  else:
    ax.hist(m.arr, int(num_bins), range=m.bounds)
  ax.axis('off')
  fig.subplots_adjust(top=1,bottom=0,right=1,left=0,hspace=0,wspace=0)
  ax.margins(0, 0)
  ax.xaxis.set_major_locator(NullLocator())
  ax.yaxis.set_major_locator(NullLocator())
  # save it as a base64 encoded string
  img_data = BytesIO()
  fig.savefig(img_data, format='png', bbox_inches='tight', pad_inches=0)
  return b64encode(img_data.getvalue())
Ejemplo n.º 2
0
def draw_figure(canvas, figure, loc=(0, 0)):
    """ Draw a matplotlib figure onto a Tk canvas

    loc: location of top-left corner of figure on canvas in pixels.
    Inspired by matplotlib source: lib/matplotlib/backends/backend_tkagg.py
    """
    figure_canvas_agg = FigureCanvasAgg(figure)
    figure_canvas_agg.draw()
    figure_x, figure_y, figure_w, figure_h = figure.bbox.bounds
    figure_w, figure_h = int(figure_w), int(figure_h)
    photo = tk.PhotoImage(master=canvas, width=figure_w, height=figure_h)

    # Position: convert from top-left anchor to center anchor
    canvas.create_image(loc[0] + figure_w / 2,
                        loc[1] + figure_h / 2,
                        image=photo)

    # Unfortunately, there's no accessor for the pointer to the native renderer
    tkagg.blit(photo, figure_canvas_agg.get_renderer()._renderer, colormode=2)

    # Return a handle which contains a reference to the photo object
    # which must be kept live or else the picture disappears
    return photo
Ejemplo n.º 3
0
def export_image(filename, format, figure, settings):
    oldSize = figure.get_size_inches()
    oldDpi = figure.get_dpi()
    figure.set_size_inches((settings.exportWidth, settings.exportHeight))
    figure.set_dpi(settings.exportDpi)

    canvas = FigureCanvasAgg(figure)
    canvas.draw()
    renderer = canvas.get_renderer()
    if matplotlib.__version__ >= '1.2':
        buf = renderer.buffer_rgba()
    else:
        buf = renderer.buffer_rgba(0, 0)
    size = canvas.get_width_height()
    image = Image.frombuffer('RGBA', size, buf, 'raw', 'RGBA', 0, 1)
    image = image.convert('RGB')
    ext = File.get_type_ext(format, File.Types.IMAGE)
    image.save(filename,
               format=ext[1::],
               dpi=(settings.exportDpi, settings.exportDpi))

    figure.set_size_inches(oldSize)
    figure.set_dpi(oldDpi)
Ejemplo n.º 4
0
def plot_LOSS(file_name, skip_points, train_loss_list, val_loss_list,
              norm_loss_list, abnorm_loss_list):
    import matplotlib.pyplot as plt
    from matplotlib.backends.backend_agg import FigureCanvasAgg
    from matplotlib.figure import Figure
    fig_size = (8, 6)
    fig = Figure(figsize=fig_size)
    file_name = file_name
    ax = fig.add_subplot(111)
    if len(train_loss_list) < skip_points:
        return
    ax.plot(train_loss_list[skip_points:])
    ax.plot(val_loss_list[skip_points:])
    ax.plot(norm_loss_list[skip_points:])
    ax.plot(abnorm_loss_list[skip_points:])
    title = os.path.basename(os.path.dirname(file_name))
    ax.set_title(title)
    ax.set_xlabel('Iterations/100')
    ax.set_ylabel('MSE')
    ax.legend(['Train', 'Valid', 'T-norm', 'T-Abnorm'])
    ax.set_xlim([0, len(train_loss_list)])
    canvas = FigureCanvasAgg(fig)
    canvas.print_figure(file_name, dpi=100)
Ejemplo n.º 5
0
def plot_hist(file_name, x, y):
    import matplotlib.pyplot as plt
    from matplotlib.backends.backend_agg import FigureCanvasAgg
    from matplotlib.figure import Figure
    kwargs = dict(alpha=0.6, bins=100, density=False, stacked=True)
    fig_size = (8, 6)
    fig = Figure(figsize=fig_size)
    file_name = file_name
    ax = fig.add_subplot(111)
    # 	x = np.exp(-x)
    # 	y = np.exp(-y)
    ax.hist(x, **kwargs, color='g', label='Norm')
    ax.hist(y, **kwargs, color='r', label='Anomaly')
    title = os.path.basename(os.path.dirname(file_name))
    ax.set_title(title)
    ax.set_xlabel('Error')
    ax.set_ylabel('Frequency')
    ax.legend(['Norm', 'Anomaly'])
    ax.set_xlim(
        [np.min(np.concatenate([x, y])),
         np.max(np.concatenate([x, y]))])
    canvas = FigureCanvasAgg(fig)
    canvas.print_figure(file_name, dpi=100)
Ejemplo n.º 6
0
def encode_plot(P, pad=None, pad_inches=0.1, bbox_inches=None):
    """
    Convert a plot object to base64-encoded png format.

    pad is passed down to matplotlib's tight_layout; pad_inches and bbox_inches to savefig.

    The resulting object is a base64-encoded version of the png
    formatted plot, which can be displayed in web pages with no
    further intervention.
    """
    from StringIO import StringIO
    from matplotlib.backends.backend_agg import FigureCanvasAgg
    from base64 import b64encode
    from urllib import quote

    virtual_file = StringIO()
    fig = P.matplotlib()
    fig.set_canvas(FigureCanvasAgg(fig))
    if pad is not None:
        fig.tight_layout(pad=pad)
    fig.savefig(virtual_file, format='png', pad_inches=pad_inches, bbox_inches=bbox_inches)
    virtual_file.seek(0)
    return "data:image/png;base64," + quote(b64encode(virtual_file.buf))
Ejemplo n.º 7
0
def plot_prediction_zx(file_name, ph_vol, gt_vol, pr_vol, z_index, x_index):
    import matplotlib.pyplot as plt
    from matplotlib.backends.backend_agg import FigureCanvasAgg
    from matplotlib.figure import Figure
    import random
    z_index, x_index = z_index, x_index
    widths = [1, 1, 1]
    heights = [1, 0.34]
    gs_kw = dict(width_ratios=widths, height_ratios=heights)
    rows, cols, size = 2, 3, 5
    fig = Figure(tight_layout=True, figsize=(size * cols, size * rows))
    kx = fig.subplots(nrows=rows, ncols=cols, gridspec_kw=gs_kw)
    ax, bx, cx = kx[0, 0], kx[0, 1], kx[0, 2]
    ex, fx, gx = kx[1, 0], kx[1, 1], kx[1, 2]
    print(ph_vol.shape)
    cax = ax.imshow(ph_vol[z_index - 1:z_index + 2, :, :].transpose((1, 2, 0)))
    fig.colorbar(cax, ax=ax)
    cbx = bx.imshow(gt_vol[z_index - 1:z_index + 2, :, :].transpose((1, 2, 0)))
    fig.colorbar(cbx, ax=bx)
    ccx = cx.imshow(pr_vol[z_index - 1:z_index + 2, :, :].transpose((1, 2, 0)))
    fig.colorbar(ccx, ax=cx)
    ax.set_title('Phase (z={})'.format(z_index))
    bx.set_title('GT fl')
    cx.set_title('Pred fl')
    ax.set_ylabel('x')
    ax.set_xlabel('y')
    cex = ex.imshow(ph_vol[:, x_index - 1:x_index + 2, :].transpose((0, 2, 1)))
    fig.colorbar(cex, ax=ex)
    cfx = fx.imshow(gt_vol[:, x_index - 1:x_index + 2, :].transpose((0, 2, 1)))
    fig.colorbar(cfx, ax=fx)
    cgx = gx.imshow(pr_vol[:, x_index - 1:x_index + 2, :].transpose((0, 2, 1)))
    fig.colorbar(cgx, ax=gx)
    ex.set_ylabel('z')
    ex.set_title('x={}'.format(x_index))
    ex.set_xlabel('y')
    canvas = FigureCanvasAgg(fig)
    canvas.print_figure(file_name, dpi=60)
Ejemplo n.º 8
0
    def _visualize(self, detection, image):
        """Generate a visual detection for a detection with matplotlib.

        Parameters
        ----------
        - detection: dict
            A single Mask RCNN detection

        - image: ndarray
            Original image.

        Returns
        ----------
        - vis_plt_detection:
            A visual detection.

        """
        rospy.loginfo("Visualizing...")

        fig = Figure()
        canvas = FigureCanvasAgg(fig)
        axes = fig.gca()
        visualize.display_instances(image,
                                    detection['rois'],
                                    detection['masks'],
                                    detection['class_ids'],
                                    CLASS_NAMES,
                                    detection['scores'],
                                    ax=axes,
                                    class_colors=self._class_colors)
        fig.tight_layout()
        canvas.draw()
        vis_plt_detection = np.fromstring(canvas.tostring_rgb(), dtype='uint8')

        _, _, w, h = fig.bbox.bounds
        vis_plt_detection = vis_plt_detection.reshape((int(h), int(w), 3))
        return vis_plt_detection
Ejemplo n.º 9
0
def make_plot(rm, r, nmin, b, f, kmax):
    from matplotlib.figure import Figure
    from matplotlib.backends.backend_agg import FigureCanvasAgg

    figure = Figure()
    canvas = FigureCanvasAgg(figure)
    ax = figure.add_subplot(111)

    for r1, nmin1, bias, gr in zip(r, nmin, b, f):
        lines = None
        for i in range(rm.power['k'].shape[1]):
            mask = rm.power['modes'][:, i] > 0
            if i == 0:
                label='nmin = %d' % nmin1
            else:
                label= None
            if lines is None:
                color = None
            else:
                color = lines.get_color()
            lines, = ax.plot(rm.power['k'][:, i][mask],
                    (r1.power['power'].real / rm.power['power'].real)[:, i][mask], '.',
                        color=color, alpha= 0.3 - 0.7 * i / rm.power['k'].shape[1])
            lines, = ax.plot(rm.power['k'][:, i][mask],
                    (bias + gr * r1.power['mu'] ** 2)[:, i][mask],
                    label=label, color=lines.get_color())

    ax.axvline(kmax, ls='--', color='k')
    ax.legend()
    ax.set_ylim(0, numpy.max(b) * 2)
    ax.set_xlim(1e-3, kmax * 8)
    ax.set_xscale('log')
    ax.set_yscale('linear')
    ax.set_xlabel('k h/Mpc')
    ax.set_ylabel('Px / Pa')

    return figure
Ejemplo n.º 10
0
def subplots(nrows=1,
             ncols=1,
             sharex=False,
             sharey=False,
             squeeze=True,
             subplot_kw=None,
             gridspec_kw=None,
             **fig_kw):
    """
    Create a figure and a set of subplots, as in `pyplot.subplots()`.

    It works almost similar to `pyplot.subplots()`, but differ from it in that
    it does not involve any side effect as pyplot does (e.g. modifying thread
    states such as current figure or current subplot).

    (docstrings inherited from `matplotlib.pyplot.subplots`)

    """
    FigureClass = fig_kw.pop('FigureClass', Figure)
    fig = FigureClass(**fig_kw)

    # attach a new Agg canvas
    if fig.canvas is None:
        FigureCanvasAgg(fig)

    # create subplots, e.g. fig.subplots() in matplotlib 2.1+
    if not hasattr(fig, 'subplots'):
        fig.subplots = types.MethodType(mpl_figure.subplots, fig, FigureClass)

    axs = fig.subplots(nrows=nrows,
                       ncols=ncols,
                       sharex=sharex,
                       sharey=sharey,
                       squeeze=squeeze,
                       subplot_kw=subplot_kw,
                       gridspec_kw=gridspec_kw)
    return fig, axs
def save_plotSpectrum(y, Fs, image_name):
    """
    Plots a Single-Sided Amplitude Spectrum of y(t)
    """
    fig = Figure(linewidth=0.0)
    fig.set_size_inches(fig_width, fig_length, forward=True)
    Figure.subplots_adjust(fig,
                           left=fig_left,
                           right=fig_right,
                           bottom=fig_bottom,
                           top=fig_top,
                           hspace=fig_hspace)
    n = len(y)  # length of the signal

    _subplot = fig.add_subplot(2, 1, 1)
    print "Fi"
    _subplot.plot(arange(0, n), y)
    xlabel('Time')
    ylabel('Amplitude')
    _subploti_2 = fig.add_subplot(2, 1, 2)
    k = arange(n)
    T = n / Fs
    frq = k / T  # two sides frequency range
    frq = frq[range(n / 2)]  # one side frequency range

    Y = fft(y) / n  # fft computing and normalization
    Y = Y[range(n / 2)]

    _subplot_2.plot(frq, abs(Y), 'r')  # plotting the spectrum
    xlabel('Freq (Hz)')
    ylabel('|Y(freq)|')
    print "here"
    canvas = FigureCanvasAgg(fig)
    if '.eps' in outfile_name:
        canvas.print_eps(outfile_name, dpi=110)
    if '.png' in outfile_name:
        canvas.print_figure(outfile_name, dpi=110)
Ejemplo n.º 12
0
    def print_drp(self, event):
        '''
        Plots a red circle and shows current DRP.
        '''
        locX, locY = event.x, event.y

        x = np.clip(locX / self.sc, 0, self.ry - 1).astype('int')
        y = np.clip(locY / self.sc, 0, self.rx - 1).astype('int')

        # Display locator (red circle)
        self.canvas.delete(self.locator)
        self.locator = self.canvas.create_oval(
            locX - 5,
            locY - 5,
            locX + 5,
            locY + 5,
            outline='red',
            width=2,
        )

        # Print DRP in canvas
        drp = self.data[y, x].reshape((self.s0, self.s1)).T
        fig = plot3D(drp, self.s0, self.s1)
        plt.close()

        # ### OPTIONAL: PRINT DRP IN CONSOLE
        # fig, ax = plt.subplots(figsize=(8,8), dpi=200)
        # ax.imshow(drp.T, cmap=plt.cm.gray)
        # ax.axis('off')
        # plt.show()

        self.drpfixim = FigureCanvasAgg(fig)
        s, (width, height) = self.drpfixim.print_to_buffer()
        self.drpfixim = np.frombuffer(s, np.uint8).reshape((height, width, 4))

        self.host_canvas.show_rgba(self.drpfixim)
        self.master_object.nbk.select(0)
Ejemplo n.º 13
0
def pcolormesh_response(lon, lat, data, request, dpi=80):
    bbox, width, height, colormap, cmin, cmax, crs = _get_common_params(
        request)

    EPSG4326 = pyproj.Proj(init='EPSG:4326')
    x, y = pyproj.transform(EPSG4326, crs, lon, lat)
    fig = Figure(dpi=dpi, facecolor='none', edgecolor='none')
    fig.set_alpha(0)
    fig.set_figheight(height / dpi)
    fig.set_figwidth(width / dpi)
    ax = fig.add_axes([0., 0., 1., 1.], xticks=[], yticks=[])
    ax.set_axis_off()

    if request.GET['logscale'] is True:
        norm_func = mpl.colors.LogNorm
    else:
        norm_func = mpl.colors.Normalize

    if cmin and cmax:
        data[data > cmax] = cmax
        data[data < cmin] = cmin
        norm = norm = norm_func(vmin=cmin, vmax=cmax)
    else:
        norm = norm_func()

    masked = np.ma.masked_invalid(data)
    ax.pcolormesh(x, y, masked, norm=norm, cmap=colormap)
    ax.set_xlim(bbox.minx, bbox.maxx)
    ax.set_ylim(bbox.miny, bbox.maxy)
    ax.set_frame_on(False)
    ax.set_clip_on(False)
    ax.set_position([0., 0., 1., 1.])

    canvas = FigureCanvasAgg(fig)
    response = HttpResponse(content_type='image/png')
    canvas.print_png(response)
    return response
Ejemplo n.º 14
0
def contourf_response(lon,
                      lat,
                      data,
                      request,
                      dpi=80
                      ):
    params = _get_common_params(request)
    bbox, width, height, colormap, cmin, cmax, crs = params
    EPSG4326 = pyproj.Proj(init='EPSG:4326')
    x, y = pyproj.transform(EPSG4326, crs, lon, lat)
    fig = Figure(dpi=dpi, facecolor='none', edgecolor='none')
    fig.set_alpha(0)
    fig.set_figheight(height/dpi)
    fig.set_figwidth(width/dpi)
    ax = fig.add_axes([0., 0., 1., 1.], xticks=[], yticks=[])
    ax.set_axis_off()
    cmap = mpl.cm.get_cmap(colormap)

    if cmin and cmax:
        data[data > cmax] = cmax
        data[data < cmin] = cmin
        bounds = np.linspace(cmin, cmax, 15)
        norm = mpl.colors.BoundaryNorm(bounds, cmap.N)
        bounds = np.linspace(cmin, cmax, 15)
    else:
        norm = None
    ax.contourf(x, y, data, vmin=5, vmax=30, norm=norm)
    ax.set_xlim(bbox.minx, bbox.maxx)
    ax.set_ylim(bbox.miny, bbox.maxy)
    ax.set_frame_on(False)
    ax.set_clip_on(False)
    ax.set_position([0., 0., 1., 1.])

    canvas = FigureCanvasAgg(fig)
    response = HttpResponse(content_type='image/png')
    canvas.print_png(response)
    return response
Ejemplo n.º 15
0
def plot():
    import matplotlib as mpl
    import matplotlib.backends.tkagg as tkagg
    from matplotlib.backends.backend_agg import FigureCanvasAgg
    from matplotlib.backends.backend_tkagg import (FigureCanvasTkAgg,
                                                   NavigationToolbar2Tk)
    import pandas as pd

    fig = mpl.figure.Figure(figsize=(3, 2))

    ax = fig.add_subplot(111)

    figure_canvas_agg = FigureCanvasAgg(fig)

    series = pandas.Series(data)
    dplt = series.plot(ax=ax)

    figure_canvas_agg.draw()
    figure_x, figure_y, figure_w, figure_h = fig.bbox.bounds
    figure_w, figure_h = int(figure_w), int(figure_h)
    global the_fig_photo
    the_fig_photo = tk.PhotoImage(master=the_canvas,
                                  width=figure_w,
                                  height=figure_h)

    # Position: convert from top-left anchor to center anchor
    loc = (0, 0)
    the_canvas.delete("all")
    the_canvas.create_image(loc[0] + figure_w / 2,
                            loc[1] + figure_h / 2,
                            image=the_fig_photo)

    tkagg.blit(the_fig_photo,
               figure_canvas_agg.get_renderer()._renderer,
               colormode=2)

    return the_fig_photo  # XXX: has to be held
Ejemplo n.º 16
0
def provincia():
    datamodel.updater(data)  # Call to update

    fig = Figure(figsize=(15, 6))

    ax = fig.add_subplot(1, 1, 1)

    provs = []

    provs_values = []

    for i, v in enumerate(data.locations):
        if v[0] != None:
            provs.append(str(v[0]))
        else:
            provs.append('Desconocido')

        provs_values.append(v[1])

        label = "{} ({}%)".format(
            v[1], round(v[1] * 100 / data.total_diagnosticados, 2))

        ax.annotate(label, (v[1], i),
                    textcoords='offset points',
                    xytext=(2, -3),
                    ha='left')

    ax.barh(provs, provs_values, color=red)

    ax.set_title('Casos detectados por provincias', fontsize=20)

    FigureCanvasAgg(fig).print_png('provincias.png')

    apiurl = config.SERVER_URI + '/provincias'
    watermark_text('provincias.png', 'provincias.png', apiurl, (0, 0))

    return send_file('provincias.png')
Ejemplo n.º 17
0
def draw_four_up_histogram(dataset) : 
    # draw a 2x2 plot of 
    #      fullpage+rast 300+rast
    #      fullpage+vor  300_vor

    outfilename = "{0}_2x2.png".format(dataset)

    figure_label_iter = iter(("(a)","(b)","(c)","(d)"))

    subplot_counter = 1
    for algo in algorithm_list : 
        for stripsize in ("fullpage","300") : 
            fig = Figure()
            fig.suptitle(dataset)

            metrics = datfile.load_metrics( dataset=dataset, stripsize=stripsize, 
                                                algorithm=algo)

            ax = fig.add_subplot(111)

            ax.hist(metrics[np.nonzero(np.nan_to_num(metrics))],bins=25)
#            ax.hist(metrics[np.nonzero(np.nan_to_num(metrics))],bins=25,normed=True)

#            ax.set_title("{0} {1} {2}".format(figure_label_iter.next(),algo,stripsize))
            ax.set_xlabel( "Metric" )
            ax.set_xlim(0,1.0)

            subplot_counter += 1

            fig.tight_layout(pad=2.0)

            outfilename = "{0}_{1}_{2}_histo.png".format(dataset,stripsize,algo)
            canvas = FigureCanvasAgg(fig)
            canvas.print_figure(outfilename)
            print "wrote", outfilename

            stretch_width( outfilename )
Ejemplo n.º 18
0
    def GET(self, from_date_str=None):
        default_from_date = TradeTime.get_latest_trade_date() - datetime.timedelta(60)
        if from_date_str is None or from_date_str == '':
            from_date = default_from_date
        else:
            try:
                input_from_date = datetime.datetime.strptime(from_date_str, '%Y-%m-%d').date()
                from_date = TradeTime.get_from_date_by_window(22, input_from_date)
            except Exception:
                from_date = default_from_date
        records_svxy = YahooEquityDAO().get_all_equity_price_by_symbol('SVXY', from_date.strftime('%Y-%m-%d'), 'Closeprice')
        dates = map(lambda x: x[0], records_svxy)
        price_svxy = map(lambda x: x[1], records_svxy)

        # shift
        append_dates = TradeTime.generate_dates(dates[-1], dates[-1] + datetime.timedelta(days=50))
        dates = dates[21:] + append_dates[1:22]
        price_svxy = price_svxy[21:] + [price_svxy[-1]] * 21

        if from_date < default_from_date:
            dates = dates[:42]
            price_svxy = price_svxy[:42]

        fig = Figure(figsize=[24, 4])
        ax = fig.add_axes([.1, .1, .8, .8])
        ax.plot(dates, price_svxy, label='SVXY')
        ax.legend(loc='upper left')
        ax.grid()
        ax.xaxis.set_major_formatter(DateFormatter('%y%m%d'))
        ax.set_xticks(dates)
        for tick in ax.get_xticklabels():
            tick.set_rotation(45)
        canvas = FigureCanvasAgg(fig)
        buf = cStringIO.StringIO()
        canvas.print_png(buf)
        data = buf.getvalue()
        return data
Ejemplo n.º 19
0
def img_home(request):
    import matplotlib.pyplot as plt
    import cartopy.crs as ccrs
    import cartopy.feature as cfeature

    fig = plt.figure(figsize=(12, 8))
    FigureCanvasAgg(fig)
    buf = io.BytesIO()
    ax = fig.add_subplot(1, 1, 1, projection=ccrs.PlateCarree())

    ax.set_global()
    ax.stock_img()

    ax.add_feature(cfeature.LAND, color='wheat')
    ax.add_feature(cfeature.OCEAN, color='skyblue')
    ax.add_feature(cfeature.COASTLINE, linestyle='-', lw=1)
    ax.add_feature(cfeature.BORDERS, linestyle=':')
    ax.add_feature(cfeature.LAKES, alpha=0.5, color='y')
    ax.add_feature(cfeature.RIVERS, color='skyblue', alpha=0.3)
    ax.plot(18.4241,
            -33.9249,
            'o',
            transform=ccrs.Geodetic(),
            markersize=7,
            color='r',
            alpha=0.3)
    plt.text(18.4241,
             -33.9249,
             'Cape Town',
             size=10,
             color='indigo',
             horizontalalignment='left',
             transform=ccrs.Geodetic())
    plt.savefig(buf, format='png')
    plt.close(fig)
    response = HttpResponse(buf.getvalue(), content_type='image/png')
    return response
Ejemplo n.º 20
0
def graph_cpu(graph_type):
    fig = plt.figure(figsize=(9, 8))
    plt.xlabel("time")
    plt.xticks(rotation=45)

    if (graph_type == "temp"):
        plt.title('temperature')
        plt.ylabel("temperature [℃]")
    elif (graph_type == "clock"):
        plt.title('clock')
        plt.ylabel("clock [GHz]")
    elif (graph_type == "volt"):
        plt.title('volt')
        plt.ylabel("volt [v]")
    elif (graph_type == "arm"):
        plt.title('arm')
        plt.ylabel("arm [MB]")
    elif (graph_type == "gpu"):
        plt.title('gpu')
        plt.ylabel("gpu [MB]")
    try:
        Data = get_graph_Data(graph_type)
        plt.plot(Data[0], Data[1])
        # canvasにプロットした画像を出力
        canvas = FigureCanvasAgg(fig)
        png_output = BytesIO()
        canvas.print_png(png_output)
        data = png_output.getvalue()
        # HTML側に渡すレスポンスを生成する
        response = make_response(data)
        response.headers['Content-Type'] = 'image/png'
        response.headers['Content-Length'] = len(data)
        return response
    except:
        flash("graph error")
        update_CPU()
        graph_cpu(graph_type)
Ejemplo n.º 21
0
def encode_plot(P,
                pad=None,
                pad_inches=0.1,
                bbox_inches=None,
                remove_axes=False,
                transparent=False,
                axes_pad=None):
    """
    Convert a plot object to base64-encoded png format.

    pad is passed down to matplotlib's tight_layout; pad_inches and bbox_inches to savefig.

    The resulting object is a base64-encoded version of the png
    formatted plot, which can be displayed in web pages with no
    further intervention.
    """
    from io import BytesIO as IO
    from matplotlib.backends.backend_agg import FigureCanvasAgg
    from base64 import b64encode
    from urllib.parse import quote

    virtual_file = IO()
    fig = P.matplotlib(axes_pad=axes_pad)
    fig.set_canvas(FigureCanvasAgg(fig))
    if remove_axes:
        for a in fig.axes:
            a.axis('off')
    if pad is not None:
        fig.tight_layout(pad=pad)
    fig.savefig(virtual_file,
                format='png',
                pad_inches=pad_inches,
                bbox_inches=bbox_inches,
                transparent=transparent)
    virtual_file.seek(0)
    buf = virtual_file.getbuffer()
    return "data:image/png;base64," + quote(b64encode(buf))
Ejemplo n.º 22
0
def test():
    datamodel.updater(data)  # Call to update

    fig = Figure(figsize=(15, 6))

    (ax1, ax2) = fig.subplots(1, 2)

    # Test realizados
    xss = [str(k) for k in range(12, data.cant_days + 1)]
    xs = range(0, data.cant_days + 1 - 12)

    ax1.bar(xss, data.cant_tests, color=red)
    ax1.bar(xss, data.detected_acc, color=yellow)

    for x, y in zip(xs, data.cant_tests):
        label = "{}".format(y)

        ax1.annotate(label, (x, y),
                     textcoords='offset points',
                     xytext=(0, 4),
                     ha='center')

    ax1.set_title('Tests acumulados por d铆a')

    # Proporci贸n entre casos confirmados y test realizados
    ax2.bar([str(k) for k in range(12, data.cant_days + 1)],
            data.prop_test_vs_detected,
            color=red)

    ax2.set_title('Proporci贸n detectados/tests realizados')

    FigureCanvasAgg(fig).print_png('tests.png')

    apiurl = config.SERVER_URI + '/test'
    watermark_text('tests.png', 'tests.png', apiurl, (0, 0))

    return send_file('tests.png')
Ejemplo n.º 23
0
def matplotlib_figure(width, height):
    """
  @brief Create a Matplotlib figure with specified width and height for rendering
  @param w Width of desired plot
  @param h Height of desired plot
  @return A Matplotlib figure
  """
    try:
        from matplotlib.backends.backend_agg import FigureCanvasAgg
    except:
        paraview.print_error(
            "Error: Cannot import matplotlib.backends.backend_agg.FigureCanvasAgg"
        )
    try:
        from matplotlib.figure import Figure
    except:
        paraview.print_error("Error: Cannot import matplotlib.figure.Figure")

    figure = Figure()
    figureCanvas = FigureCanvasAgg(figure)
    figure.set_dpi(72)
    figure.set_size_inches(float(width) / 72.0, float(height) / 72.0)

    return figure
Ejemplo n.º 24
0
    def makeTextGraph(self, text='Empty image'):
        """ Make an empty text image
    """

        self.figure = Figure()
        figure = self.figure
        self.canvas = FigureCanvasAgg(figure)

        prefs = self.prefs
        dpi = prefs['dpi']
        width = float(prefs['width'])
        height = float(prefs['height'])
        width_inch = width / dpi
        height_inch = height / dpi
        figure.set_size_inches(width_inch, height_inch)
        figure.set_dpi(dpi)
        figure.set_facecolor('white')

        text_size = prefs.get('text_size', 12)
        figure.text(.5,
                    .5,
                    text,
                    horizontalalignment='center',
                    size=pixelToPoint(text_size, dpi))
Ejemplo n.º 25
0
def spec_plot(x, y, img, file_name, figure_size=(10, 5), transparent=False):
    import matplotlib
    import matplotlib.figure
    import matplotlib.cm
    from matplotlib.backends.backend_agg import FigureCanvasAgg
    figure_size = None

    F = first_moment_analysis(x, y)

    fig = matplotlib.figure.Figure(figure_size,
                                   144,
                                   linewidth=0,
                                   facecolor="white")
    if transparent:
        self.figure.figurePatch.set_alpha(0.0)
    canvas = FigureCanvasAgg(fig)
    p = fig.add_subplot(211)
    p.set_position([0.1, 0.3, 0.8, 0.6])
    p.plot(x, y, '-')
    fm = F.as_trace()
    p.plot(fm[0], fm[1], "r-")
    p.set_xlim(x[0], x[-1])
    p.set_xlabel("position")
    p.set_ylabel("intensity")
    p.set_title("X-ray emission spectrum, first moment=%.2f" %
                (F.first_moment))
    p2 = fig.add_subplot(212)
    p2.set_position([0.1, 0.05, 0.8, 0.2])
    im = p2.imshow(img.as_numpy_array(), cmap='spectral')
    im.set_interpolation("none")
    position = fig.add_axes([0.91, 0.1, 0.015, 0.35])
    #  p2.imshow(img.as_numpy_array(), cmap=matplotlib.cm.gist_yarg)
    p3 = fig.colorbar(im, orientation='vertical', cax=position)
    #  p2.set_position([0.1, 0.05, 0.8, 0.2])
    canvas.draw()
    fig.savefig(file_name, dpi=200, format="png")
Ejemplo n.º 26
0
def plot():
    """ SQL query and plot graph

    Connect to the Azure SQL Database and making a query.
    Then use the query result to plot a graph.
    This graph will be used by the hello.html.
    """

    # Connect to the Azure SQL database
    driver, server, db, uid, pwd = configuration()
    conn, cursor = sqldb_conn(driver, server, db, uid, pwd)

    # Making the SQL query
    query = fetch_query()

    # Putting the result in a dataframe
    df = pd.read_sql(query, conn)

    # Call the create_figure method from graph.py to plot a graph
    fig = create_figure(df)

    output = io.BytesIO()
    FigureCanvasAgg(fig).print_png(output)
    return Response(output.getvalue(), mimetype='image/png')
Ejemplo n.º 27
0
def mathTex_to_QPixmap(mathTex, font_size):

    #---- set up a mpl figure instance ----

    fig = mpl.figure.Figure()
    fig.patch.set_facecolor('none')
    fig.set_canvas(FigureCanvasAgg(fig))
    renderer = fig.canvas.get_renderer()

    #---- plot the mathTex expression ----

    ax = fig.add_axes([0, 0, 1, 1])
    ax.axis('off')
    ax.patch.set_facecolor('none')
    t = ax.text(0, 0, mathTex, ha='left', va='bottom', fontsize=font_size)

    #---- fit figure size to text artist ----

    fwidth, fheight = fig.get_size_inches()
    fig_bbox = fig.get_window_extent(renderer)

    text_bbox = t.get_window_extent(renderer)

    tight_fwidth = text_bbox.width * fwidth / fig_bbox.width
    tight_fheight = text_bbox.height * fheight / fig_bbox.height

    fig.set_size_inches(tight_fwidth, tight_fheight)

    #---- convert mpl figure to QPixmap ----

    buf, size = fig.canvas.print_to_buffer()
    qimage = QtGui.QImage.rgbSwapped(QtGui.QImage(buf, size[0], size[1],
                                                  QtGui.QImage.Format_ARGB32))
    qpixmap = QtGui.QPixmap(qimage)

    return qpixmap
Ejemplo n.º 28
0
def plot_dsc(dsc_dist):
    y_positions = np.arange(len(dsc_dist))
    dsc_dist = sorted(dsc_dist.items(), key=lambda x: x[1])
    values = [x[1] for x in dsc_dist]
    labels = [x[0] for x in dsc_dist]
    labels = ["_".join(l.split("_")[1:-1]) for l in labels]
    fig = plt.figure(figsize=(12, 8))
    canvas = FigureCanvasAgg(fig)
    plt.barh(y_positions, values, align="center", color="skyblue")
    plt.yticks(y_positions, labels)
    plt.xticks(np.arange(0.0, 1.0, 0.1))
    plt.xlim([0.0, 1.0])
    plt.gca().axvline(np.mean(values), color="tomato", linewidth=2)
    plt.gca().axvline(np.median(values), color="forestgreen", linewidth=2)
    plt.xlabel("Dice coefficient", fontsize="x-large")
    plt.gca().xaxis.grid(color="silver",
                         alpha=0.5,
                         linestyle="--",
                         linewidth=1)
    plt.tight_layout()
    canvas.draw()
    plt.close()
    s, (width, height) = canvas.print_to_buffer()
    return np.fromstring(s, np.uint8).reshape((height, width, 4))
Ejemplo n.º 29
0
def plot_psnr_histogram(file_name, psnr_list1, psnr_list2, rho_list1, rho_list2):
	import matplotlib.pyplot as plt
	from matplotlib.backends.backend_agg import FigureCanvasAgg
	from matplotlib.figure import Figure
	kwargs = dict(alpha=0.7, bins=12, density= False, stacked=True)
	rows, cols, size = 1,2,6; font_size = 20
	fig = Figure(tight_layout=True,figsize=(size*cols, size*rows)); ax = fig.subplots(rows,cols)
	ax[0].hist(psnr_list1, **kwargs, color='r', label='fl1') # PSNR for channel 1
	ax[0].hist(psnr_list2, **kwargs, color='g', label='fl2') # PSNR for channel 2
	ax[0].legend(['fl1_average: {:.2f}'.format(np.mean(psnr_list1)), 'fl2_average: {:.2f}'.format(np.mean(psnr_list2))],fontsize=font_size-2)
	ax[0].set_title('PSNR distribution', fontsize =font_size)
	ax[0].set_ylabel('Count', fontsize =font_size);ax[0].set_xlabel('PSNR', fontsize =font_size);
	ax[0].set_xlim([np.min(np.concatenate([psnr_list1,psnr_list2]))-5, np.max(np.concatenate([psnr_list1,psnr_list2]))])	
# 	ax[0].set_xlim([np.min(np.concatenate([psnr_list1,psnr_list2])), np.max(np.concatenate([psnr_list1,psnr_list2]))])
	ax[0].tick_params(axis='x', labelsize=font_size-2); ax[0].tick_params(axis='y', labelsize=font_size-2)
# 	kwargs = dict(alpha=0.9, bins=10, density= False, stacked=True)
	ax[1].hist(rho_list1, **kwargs, color='r', label='fl1') # PSNR for channel 1
	ax[1].hist(rho_list2, **kwargs, color='g', label='fl2') # PSNR for channel 2
	ax[1].set_title(r'$\rho$ distribution', fontsize =font_size)
	ax[1].set_ylabel('Count', fontsize =font_size);ax[1].set_xlabel(r'$\rho$', fontsize =font_size);
	ax[1].tick_params(axis='x', labelsize=font_size-2); ax[1].tick_params(axis='y', labelsize=font_size-2)
	ax[1].set_xlim([0,1.0])
	ax[1].legend(['fl1_average: {:.4f}'.format(np.mean(rho_list1)), 'fl2_average: {:.4f}'.format(np.mean(rho_list2))],fontsize=font_size-2)
	canvas = FigureCanvasAgg(fig); canvas.print_figure(file_name, dpi=80)
Ejemplo n.º 30
0
def write_report(reportname, r):
    from matplotlib.figure import Figure
    from matplotlib.backends.backend_agg import FigureCanvasAgg
    fig = Figure(figsize=(6, 6))
    ax = fig.add_subplot(111)
    ax.plot(r.Ppm.power['k'],
            r.Ppm.power['power'] / r.Pl.power['power'] - 1,
            label='Multistep')
    ax.plot(r.P1lpt.power['k'],
            r.P1lpt.power['power'] / r.Pl.power['power'] - 1,
            label='1-LPT')
    ax.set_xscale('log')
    ax.axhline(0.0, color='k', ls='--')
    ax.set_ylim(-0.03, 0.03)
    ax.set_xlim(0.003, 0.04)
    ax.grid()
    ax.set_xlabel('k [h/Mpc]')
    ax.set_ylabel(r'P(k) / <P_l(k)>')
    ax.set_title(r"Comparing Linear theory and 1-LPT")
    ax.legend()

    #    numpy.savez(reportname.replace('.png', '.npz', r.__dict__)
    canvas = FigureCanvasAgg(fig)
    fig.savefig(reportname)