当前位置: 首页>>代码示例>>Python>>正文


Python Figure.get_facecolor方法代码示例

本文整理汇总了Python中matplotlib.figure.Figure.get_facecolor方法的典型用法代码示例。如果您正苦于以下问题:Python Figure.get_facecolor方法的具体用法?Python Figure.get_facecolor怎么用?Python Figure.get_facecolor使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在matplotlib.figure.Figure的用法示例。


在下文中一共展示了Figure.get_facecolor方法的14个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: test_repeated_save_with_alpha

# 需要导入模块: from matplotlib.figure import Figure [as 别名]
# 或者: from matplotlib.figure.Figure import get_facecolor [as 别名]
def test_repeated_save_with_alpha():
    # We want an image which has a background color of bluish green, with an
    # alpha of 0.25.

    fig = Figure([1, 0.4])
    fig.set_facecolor((0, 1, 0.4))
    fig.patch.set_alpha(0.25)

    # The target color is fig.patch.get_facecolor()

    buf = io.BytesIO()

    fig.savefig(buf,
                facecolor=fig.get_facecolor(),
                edgecolor='none')

    # Save the figure again to check that the
    # colors don't bleed from the previous renderer.
    buf.seek(0)
    fig.savefig(buf,
                facecolor=fig.get_facecolor(),
                edgecolor='none')

    # Check the first pixel has the desired color & alpha
    # (approx: 0, 1.0, 0.4, 0.25)
    buf.seek(0)
    assert_array_almost_equal(tuple(imread(buf)[0, 0]),
                              (0.0, 1.0, 0.4, 0.250),
                              decimal=3)
开发者ID:anntzer,项目名称:matplotlib,代码行数:31,代码来源:test_agg.py

示例2: test_repeated_save_with_alpha

# 需要导入模块: from matplotlib.figure import Figure [as 别名]
# 或者: from matplotlib.figure.Figure import get_facecolor [as 别名]
def test_repeated_save_with_alpha():
    # We want an image which has a background color of bluish green, with an
    # alpha of 0.25.

    fig = Figure([1, 0.4])
    canvas = FigureCanvas(fig)
    fig.set_facecolor((0, 1, 0.4))
    fig.patch.set_alpha(0.25)

    # The target color is fig.patch.get_facecolor()

    _, img_fname = tempfile.mkstemp(suffix='.png')
    try:
        fig.savefig(img_fname,
                    facecolor=fig.get_facecolor(),
                    edgecolor='none')

        # Save the figure again to check that the
        # colors don't bleed from the previous renderer.
        fig.savefig(img_fname,
                    facecolor=fig.get_facecolor(),
                    edgecolor='none')

        # Check the first pixel has the desired color & alpha
        # (approx: 0, 1.0, 0.4, 0.25)
        assert_array_almost_equal(tuple(imread(img_fname)[0, 0]),
                                  (0.0, 1.0, 0.4, 0.250),
                                  decimal=3)
    finally:
        os.remove(img_fname)
开发者ID:JunOu,项目名称:matplotlib,代码行数:32,代码来源:test_agg.py

示例3: bargraph

# 需要导入模块: from matplotlib.figure import Figure [as 别名]
# 或者: from matplotlib.figure.Figure import get_facecolor [as 别名]
def bargraph(request):
    p = request.GET    

    try:
        d = [(float(p['d10']), float(p['d11']), float(p['d12']), float(p['d13']), float(p['d14'])),
             (float(p['d20']), float(p['d21']), float(p['d22']), float(p['d23']), float(p['d24'])),
             (float(p['d30']), float(p['d31']), float(p['d32']), float(p['d33']), float(p['d34'])),
             (float(p['d40']), float(p['d41']), float(p['d42']), float(p['d43']), float(p['d44'])),
             (float(p['d50']), float(p['d51']), float(p['d52']), float(p['d53']), float(p['d54'])),
             (float(p['d60']), float(p['d61']), float(p['d62']), float(p['d63']), float(p['d64'])),
             (float(p['d70']), float(p['d71']), float(p['d72']), float(p['d73']), float(p['d74'])),
             (float(p['d80']), float(p['d81']), float(p['d82']), float(p['d83']), float(p['d84']))]
    except:
        return render(request,"bad.html", { 'type':'bargraph' })

    tickM = ["2. Culture for retreatment",
         "3. GeneXpert for HIV positive only", 
         "4. GeneXpert for smear positive only", 
         "5. GeneXpert for all",
         "6. GeneXpert for all, culture confirmed",
         "7. MODS/TLA",
         "8. Same-day smear microscopy",
         "9. Same-day GeneXpert"]

    colors = ["grey","blue","green","yellow","red"]

    ndata = zip(*d)

    loc = np.arange(len(ndata[0]))
    width = 0.15

    fig = Figure(facecolor='white')
    canvas = FigureCanvas(fig)

    ax = fig.add_subplot(111)

    rect = [ax.bar(loc+width*i, ndata[i], width, color=colors[i]) 
            for i in range(len(ndata))]

    ax.set_ylim(-50,100)
    ax.set_xlim(-width*4, len(loc) +(4*width))

    ax.set_xticks(loc + (2.5*width))

    ax.set_xticklabels(tickM, rotation='30', size='small', stretch='condensed',
                       ha='right' )

    ax.legend ((rect[0][0], rect[1][0], rect[2][0], rect[3][0], rect[4][0]),
                ("TBInc", "MDRInc", "TBMort", "Yr1Cost", "Yr5Cost"),loc='best')

    ax.set_title ("Graph Comparison")
    ax.axhline(color='black')

    ax.set_ylabel('percentage change from baseline')

    fig.tight_layout()

    response=HttpResponse(content_type='image/png')
    canvas.print_png(response,facecolor=fig.get_facecolor())
    return response
开发者ID:JJPennington,项目名称:FlexDx-TB-Web-Django,代码行数:62,代码来源:views.py

示例4: dgraph1

# 需要导入模块: from matplotlib.figure import Figure [as 别名]
# 或者: from matplotlib.figure.Figure import get_facecolor [as 别名]
def dgraph1(request):
    p_val = request.GET
    order = [0,1,7,6,2,8,3,4,5]
    try:
        cmore = [float(p_val['c{}'.format(order[x])]) for x in range(9)]
        inc = [float(p_val['i{}'.format(order[x])]) for x in range(9)]
    except:
        return render(request,"bad.html", { 'type':'dot graph 1' })
                
    fig = Figure(facecolor='white')
    canvas = FigureCanvas(fig)

    ax1 = fig.add_subplot(111)

    ax1.set_ylabel('% decrease in TB incidence at year 5 (more effective -->)')
    ax1.set_xlabel('% increase in cost at year 5 (more costly -->)')

    ax1.plot(cmore,inc,marker='.',linestyle='None')

    ax1.set_title("Percent change (%) in cost and TB incidence at year 5")

    ax1.axhline(color='r')
    ax1.axvline(color='r')

    #Add annotations, simple collision detection
    point_list = []
    for i in xrange(9):
        dx,dy = placement(cmore[i],inc[i],point_list,ax1)
        point_list.append([cmore[i],inc[i],dx,dy])
        ax1.annotate(str(i+1), xy=(cmore[i],inc[i]), 
                     xytext=(cmore[i]+dx,inc[i]+dy),
                     arrowprops=dict(color='red',arrowstyle="->"))

    fig.tight_layout()

    response=HttpResponse(content_type='image/png')
    canvas.print_png(response,facecolor=fig.get_facecolor())
    return response
开发者ID:JJPennington,项目名称:FlexDx-TB-Web-Django,代码行数:40,代码来源:views.py

示例5: PlotWidget

# 需要导入模块: from matplotlib.figure import Figure [as 别名]
# 或者: from matplotlib.figure.Figure import get_facecolor [as 别名]

#.........这里部分代码省略.........
                                                                  self.allocation.width, self.allocation.height)

            renderer = RendererCairo(self.figure.dpi)
            renderer.set_width_height(self.allocation.width, self.allocation.height)
            renderer.set_ctx_from_surface(self.cached_contents)

            self.figure.draw(renderer)

        # event.region is not bound: http://bugzilla.gnome.org/show_bug.cgi?id=487158
#        gdk_context = gtk.gdk.CairoContext(renderer.ctx)
#        gdk_context.region(event.region)
#        gdk_context.clip()

        cr.set_source_surface(self.cached_contents, 0, 0)
        cr.paint()

    def do_size_allocate(self, allocation):
        if allocation.width != self.allocation.width or allocation.height != self.allocation.height:
            self.cached_contents = None

        gtk.DrawingArea.do_size_allocate(self, allocation)

    def do_unrealize(self):
        gtk.DrawingArea.do_unrealize(self)

        self.cached_contents = None

    def do_button_press_event(self, event):
        if event.button == 3:
            custom_result.show_menu(self, event, save_callback=self.__save)
            return True
        else:
            return True
    
    def do_button_release_event(self, event):
        return True

    def do_realize(self):
        gtk.DrawingArea.do_realize(self)
        cursor = gtk.gdk.Cursor(gtk.gdk.LEFT_PTR)
        self.window.set_cursor(cursor)
    
    def do_size_request(self, requisition):
        try:
            # matplotlib < 0.98
            requisition.width = self.figure.bbox.width()
            requisition.height = self.figure.bbox.height()
        except TypeError:
            # matplotlib >= 0.98
            requisition.width = self.figure.bbox.width
            requisition.height = self.figure.bbox.height

    def recompute_figure_size(self):
        width = (self.sidebar_width / self.figure.dpi)
        height = width / DEFAULT_ASPECT_RATIO

        self.figure.set_figwidth(width)
        self.figure.set_figheight(height)

        self.queue_resize()

    def sync_dpi(self, dpi):
        self.figure.set_dpi(dpi)
        if self.sidebar_width >= 0:
            self.recompute_figure_size()

    def set_sidebar_width(self, width):
        if self.sidebar_width == width:
            return

        self.sidebar_width = width
        if self.sidebar_width >= 0:
            self.recompute_figure_size()

    def sync_style(self, style):
        self.cached_contents = None

        matplotlib.rcParams['font.size'] = self.parent.style.font_desc.get_size() / pango.SCALE

    def __save(self, filename):
        # The save/restore here was added to matplotlib's after 0.90. We duplicate
        # it for compatibility with older versions. (The code would need modification
        # for 0.98 and newer, which is the reason for the particular version in the
        # check)

        version = [int(x) for x in matplotlib.__version__.split('.')]
        need_save = version[:2] < [0, 98]
        if need_save:
            orig_dpi = self.figure.dpi.get()
            orig_facecolor = self.figure.get_facecolor()
            orig_edgecolor = self.figure.get_edgecolor()

        try:
            self.canvas.print_figure(filename)
        finally:
            if need_save:
                self.figure.dpi.set(orig_dpi)
                self.figure.set_facecolor(orig_facecolor)
                self.figure.set_edgecolor(orig_edgecolor)
                self.figure.set_canvas(self.canvas)
开发者ID:alexey4petrov,项目名称:reinteract,代码行数:104,代码来源:replot.py

示例6: make_movie

# 需要导入模块: from matplotlib.figure import Figure [as 别名]
# 或者: from matplotlib.figure.Figure import get_facecolor [as 别名]

#.........这里部分代码省略.........
                    mom_fft = galsim.utilities.unweighted_moments(fft_img, origin=fft_img.true_center)
                    e_fft = galsim.utilities.unweighted_shape(mom_fft)
                    M_fft.set_text(Is.format(mom_fft['Mx']*fft_img.scale,
                                             mom_fft['My']*fft_img.scale,
                                             mom_fft['Mxx']*fft_img.scale**2,
                                             mom_fft['Myy']*fft_img.scale**2,
                                             mom_fft['Mxy']*fft_img.scale**2))
                    etext_fft.set_text("$e_1$={: 6.4f}, $e_2$={: 6.4f}, $r^2$={:6.4f}".format(
                                       e_fft['e1'], e_fft['e2'], e_fft['rsqr']*fft_img.scale**2))
                    fft_mom[i] = (mom_fft['Mx']*fft_img.scale, mom_fft['My']*fft_img.scale,
                                  mom_fft['Mxx']*fft_img.scale**2, mom_fft['Myy']*fft_img.scale**2,
                                  mom_fft['Mxy']*fft_img.scale**2,
                                  e_fft['e1'], e_fft['e2'], e_fft['rsqr']*fft_img.scale**2)

                if args.do_geom and (args.make_movie or args.make_plots):
                    geom_im.set_array(geom_img.array)

                    mom_geom = galsim.utilities.unweighted_moments(geom_img,
                                                                   origin=geom_img.true_center)
                    e_geom = galsim.utilities.unweighted_shape(mom_geom)
                    M_geom.set_text(Is.format(mom_geom['Mx']*geom_img.scale,
                                              mom_geom['My']*geom_img.scale,
                                              mom_geom['Mxx']*geom_img.scale**2,
                                              mom_geom['Myy']*geom_img.scale**2,
                                              mom_geom['Mxy']*geom_img.scale**2))
                    etext_geom.set_text("$e_1$={: 6.4f}, $e_2$={: 6.4f}, $r^2$={:6.4f}".format(
                                        e_geom['e1'], e_geom['e2'], e_geom['rsqr']*geom_img.scale**2))
                    geom_mom[i] = (mom_geom['Mx']*geom_img.scale, mom_geom['My']*geom_img.scale,
                                  mom_geom['Mxx']*geom_img.scale**2, mom_geom['Myy']*geom_img.scale**2,
                                  mom_geom['Mxy']*geom_img.scale**2,
                                  e_geom['e1'], e_geom['e2'], e_geom['rsqr']*geom_img.scale**2)

                if args.make_movie:
                    writer.grab_frame(facecolor=fig.get_facecolor())

                bar.update()

    def symmetrize_axis(ax):
        xlim = ax.get_xlim()
        ylim = ax.get_ylim()
        lim = min(xlim[0], ylim[0]), max(xlim[1], ylim[1])
        ax.set_xlim(lim)
        ax.set_ylim(lim)
        ax.plot(lim, lim)

    if args.make_plots:
        # Centroid plot
        fig = Figure(figsize=(10, 6))
        FigureCanvasAgg(fig)
        axes = []
        axes.append(fig.add_subplot(1, 2, 1))
        axes.append(fig.add_subplot(1, 2, 2))
        axes[0].scatter(fft_mom[:, 0], geom_mom[:, 0])
        axes[1].scatter(fft_mom[:, 1], geom_mom[:, 1])
        axes[0].set_title("Mx")
        axes[1].set_title("My")
        for ax in axes:
            ax.set_xlabel("Fourier Optics")
            ax.set_ylabel("Geometric Optics")
            symmetrize_axis(ax)
        fig.tight_layout()
        fig.savefig(args.out+"centroid.png", dpi=300)

        # Second moment plot
        fig = Figure(figsize=(16, 6))
        FigureCanvasAgg(fig)
开发者ID:GalSim-developers,项目名称:GalSim,代码行数:70,代码来源:fft_vs_geom_movie.py

示例7: Days

# 需要导入模块: from matplotlib.figure import Figure [as 别名]
# 或者: from matplotlib.figure.Figure import get_facecolor [as 别名]

#.........这里部分代码省略.........
                        parent=parent,
                        dpi=self.dpi,
                        datadir=datadir)
        return


    def get_png(self, id):
        print("creating a png")
        self.save_plot("test.png")


    def on_draw(self, event):
        top = self.fig.subplotpars.top
        bottom = self.fig.subplotpars.bottom
        hspace = self.fig.subplotpars.hspace
        wspace = self.fig.subplotpars.wspace

        needs_adjusting = False

        # Calculate the area required at the top of the plot
        # (Main title and subplot title)
        subplot_title_height = 0
        main_title_height = 0

        for subplot in self.subplots:
            if subplot.is_first_row():
                bbox = subplot.title.get_window_extent()
                transformed_bbox = bbox.inverse_transformed(self.fig.transFigure)
                subplot_title_height = max(transformed_bbox.height, subplot_title_height)

        #print 'title = ', self.fig.get_label()

        bbox = self.main_title_label.get_window_extent()
        main_title_height = bbox.inverse_transformed(self.fig.transFigure).height

        preferred_top_space = 1.25*(subplot_title_height + main_title_height)

        if ((1 - top) < preferred_top_space) or (((1 - top) - preferred_top_space)>0.11):
            top = 0.99 - preferred_top_space
            needs_adjusting = True

        if needs_adjusting:
            #print 'adjusting'
            #todo if the colorbar dosn't exist, ignore this.
            self.fig.subplots_adjust(top = top, bottom = bottom, hspace = hspace, wspace = wspace)
            self.cb_ax.set_position(self.get_cb_axes())
            self.fig.canvas.draw()

        return False

    def add_legend(self, ax):
        leg = ax.legend(('MUF', 'FOT'),ncol=1)
        leg.get_frame().set_alpha(0.75)
        return leg

    def save_plot(self, filename=None):
        #canvas.print_figure(filename, dpi=150, facecolor='white', edgecolor='white')
        self.fig.savefig(filename, dpi=self.dpi, facecolor=self.fig.get_facecolor(), edgecolor='none')

    def get_cb_axes(self):
        # an equivalent of get_tightbox would be really useful here...
        #bbox = self.subplots[0].get_window_extent()
        bbox = self.subplots[0].get_yaxis().get_clip_box()
        axis_upper_y = bbox.inverse_transformed(self.fig.transFigure).ymax
        bbox = self.subplots[-1].get_window_extent()
        axis_lower_y = bbox.inverse_transformed(self.fig.transFigure).ymin
        return [0.9, axis_lower_y, 0.02, axis_upper_y-axis_lower_y]

    #def percentFormat(x, pos):
    #    'The two args are the value and tick position'
    #    return '%(percent)3d%% (%(days)d days)' % {'percent':x*100, 'days':x*30.0}
    def percent_format(self, x, pos):
        return '%(percent)3d%%' % {'percent':x*100}

    def SNR_format(self, x, pos):
        return '%3ddB' % x

    def defaultFormat(self, x, pos):
        return '%d' % x

    def SDBW_format(self, x, pos):
        S_DICT = {-151:'S1', -145:'S2', -139:'S3', -133:'S4', -127:'S5', \
                    -121:'S6', -115:'S7', -109:'S8', -103:'S9', -93:'S9+10dB', \
                    -83:'S9+20dB', -73:'S9+30dB', -63:'S9+40dB', -53:'S9+50dB', -43:'S9+60dB'}
        if x in S_DICT:
            return _('%(value)ddBW (%(s_value)s)') %{'value':x, 's_value':S_DICT[x]}
        else : return '%3d' % x

    def get_small_title(self, title_string):
    #Mar    2008          SSN =   7.                Minimum Angle= 3.000 degrees
   #RIYADH (AR RIYAD)   YORK                  AZIMUTHS          N. MI.      KM
   #24.63 N   46.71 E - 53.96 N    1.08 W    322.62  110.27    2753.7   5099.5
   #XMTR  2-30 2-D Table [default/swwhip.voa   ] Az=322.6 OFFaz=  0.0   0.005kW
   #RCVR  2-30 2-D Table [default/swwhip.voa   ] Az=110.3 OFFaz=360.0
   #3 MHz NOISE = -145.0 dBW     REQ. REL = 90%    REQ. SNR = 10.0 dB
        title_lines = title_string.split('\n')
        #Extract Month / year and SSN
        tmp_line = title_lines[0].split()
        tmp_str = tmp_line[0] + ' ' + tmp_line[1] + ' SSN:' + tmp_line[4].rstrip('.')
        return tmp_str
开发者ID:jawatson,项目名称:pythonprop,代码行数:104,代码来源:voaP2PPlot.py

示例8: _

# 需要导入模块: from matplotlib.figure import Figure [as 别名]
# 或者: from matplotlib.figure.Figure import get_facecolor [as 别名]

#.........这里部分代码省略.........
        # print self.image_defs['y_labels']
        for t in self.cb_ax.get_yticklabels():
            t.set_fontsize(colorbar_fontsize)

        canvas = FigureCanvasGTK3Agg(self.fig)
        self.fig.canvas.mpl_connect("draw_event", self.on_draw)
        canvas.show()

        if save_file:
            self.save_plot(canvas, save_file)

        # todo this ought to a command line param
        if not self.run_quietly:
            dia = VOAPlotWindow("pythonProp - " + self.image_defs["title"], canvas, parent=parent)
        return

    def on_draw(self, event):
        top = self.fig.subplotpars.top
        bottom = self.fig.subplotpars.bottom
        hspace = self.fig.subplotpars.hspace
        wspace = self.fig.subplotpars.wspace

        fig_height = self.fig.get_figheight()

        needs_adjusting = False

        # Area required at the top of the plot (Main title and subplot title)
        bbox = self.subplot_title_label.get_window_extent()
        subplot_title_bbox = bbox.inverse_transformed(self.fig.transFigure)

        bbox = self.main_title_label.get_window_extent()
        main_title_bbox = bbox.inverse_transformed(self.fig.transFigure)

        _preferred_top_space = 1.25 * (subplot_title_bbox.height + main_title_bbox.height)
        _actual_top_space = 1 - top

        if (_actual_top_space < _preferred_top_space) or ((_actual_top_space - _preferred_top_space) > 0.11):
            top = 0.99 - _preferred_top_space
            needs_adjusting = True

        if needs_adjusting:
            self.fig.subplots_adjust(top=top, bottom=bottom, hspace=hspace, wspace=wspace)
            self.cb_ax.set_position(self.get_cb_axes())
            self.fig.canvas.draw()
        return False

    def save_plot(self, canvas, filename=None):
        canvas.print_figure(filename, dpi=self.dpi, facecolor=self.fig.get_facecolor(), edgecolor="none")

    def get_cb_axes(self):
        bbox = self.subplots[0].get_window_extent()
        axis_upper_y = bbox.inverse_transformed(self.fig.transFigure).ymax
        bbox = self.subplots[-1].get_window_extent()
        axis_lower_y = bbox.inverse_transformed(self.fig.transFigure).ymin
        return [0.87, axis_lower_y, 0.02, axis_upper_y - axis_lower_y]

    def percent_format(self, x, pos):
        return "%(percent)3d%%" % {"percent": x * 100}

    def SNR_format(self, x, pos):
        return "%3ddB" % x

    def SDBW_format(self, x, pos):
        return "%3ddBW" % x

    """
    The values below are derived from material
    presented at http://www.voacap.com/s-meter.html
    """

    def SMETER_format(self, x, pos):
        print x
        S_DICT = {
            -151.18: "S1",
            -145.15: "S2",
            -139.13: "S3",
            -133.11: "S4",
            -127.09: "S5",
            -121.07: "S6",
            -115.05: "S7",
            -109.03: "S8",
            -103.01: "S9",
            -93.01: "S9+10dB",
            -83.01: "S9+20dB",
            -73.01: "S9+30dB",
            -63.01: "S9+40dB",
            -53.01: "S9+50dB",
            -43.01: "S9+60dB",
        }
        if S_DICT.has_key(x):
            return "%s" % S_DICT[x]
            # return _('%(value)ddBW (%(s_value)s)') %{'value':x, 's_value':S_DICT[x]}
        else:
            return "%3d" % x

    def frequency_format(self, x, pos):
        return "%2dMHz" % x

    def default_format(self, x, pos):
        return "%d" % x
开发者ID:G4FKH,项目名称:pythonprop,代码行数:104,代码来源:voaAreaPlot.py

示例9: bargraph_uncert

# 需要导入模块: from matplotlib.figure import Figure [as 别名]
# 或者: from matplotlib.figure.Figure import get_facecolor [as 别名]
def bargraph_uncert(request):
    p = request.GET    

    #BASIC TEST

    try:
        ca  = [float(p['ca{}'.format(x)]) for x in range(1,9)]
        cal = [float(p['cal{}'.format(x)]) for x in range(1,9)]
        cah = [float(p['cah{}'.format(x)]) for x in range(1,9)]
        cb  = [float(p['cb{}'.format(x)]) for x in range(1,9)]
        cbl = [float(p['cbl{}'.format(x)]) for x in range(1,9)]
        cbh = [float(p['cbh{}'.format(x)]) for x in range(1,9)]
        tb  = [float(p['tb{}'.format(x)]) for x in xrange(1,9)]
        tbl = [float(p['tbl{}'.format(x)]) for x in xrange(1,9)]
        tbh = [float(p['tbh{}'.format(x)]) for x in xrange(1,9)]
        mb  = [float(p['mb{}'.format(x)]) for x in xrange(1,9)]
        mbl = [float(p['mbl{}'.format(x)]) for x in xrange(1,9)]
        mbh = [float(p['mbh{}'.format(x)]) for x in range(1,9)]
        ob  = [float(p['ob{}'.format(x)]) for x in range(1,9)]
        obl = [float(p['obl{}'.format(x)]) for x in range(1,9)]
        obh = [float(p['obh{}'.format(x)]) for x in range(1,9)]
    except:
        return render(request,"bad.html", { 'type':'bargraph' })

    colors = ["grey","blue","green","yellow","red"]
    
    pdata = [ tb, mb, ob, ca, cb ]
    
    #ndata = zip(*d)

    height = max(chain(tbh,mbh,obh,cah,cbh,tb,mb,ob,ca,cb)) + 10

    #loc = np.arange(len(ndata[0])) 
    loc = np.arange(len(ca))

    width = 0.15

    fig = Figure(facecolor='white', dpi=150, figsize=(8,6))
    canvas = FigureCanvas(fig)

    ax = fig.add_subplot(111)

    rect = [ax.bar(loc+width*i, pdata[i], width, color=colors[i]) 
            for i in range(len(pdata))]

    [ax.errorbar([i+(width*.5)], tb[i], yerr=[[tb[i] - tbl[i]],[tbh[i] - tb[i]]],
                   color='black',
                   ecolor='black',
                   linewidth=1)
                   for i in xrange(8)] #TBIncidence Errorbar
    [ax.errorbar([i+(width*1.5)], mb[i], yerr=[[mb[i] - mbl[i]],[mbh[i] - mb[i]]],
                   color='black',
                   ecolor='black',
                   linewidth=1)
                   for i in xrange(8)] #MDRIncidence Errorbar
    [ax.errorbar([i+(width*2.5)], ob[i], yerr=[[ob[i] - obl[i]],[obh[i] - ob[i]]],
                   color='black',
                   ecolor='black',
                   linewidth=1)
                   for i in xrange(8)] #Mortality Errorbar
    [ax.errorbar([i+(width*3.5)], ca[i], yerr=[[ca[i] - cal[i]],[cah[i] - ca[i]]],
                   color='black',
                   ecolor='black',
                   linewidth=1)
                   for i in xrange(8)] #Cost Yr 1 Errorbar
    [ax.errorbar([i+(width*4.5)], cb[i], yerr=[[cb[i] - cbl[i]],[cbh[i] - cb[i]]],
                   color='black',
                   ecolor='black',
                   linewidth=1)
                   for i in xrange(8)] #Cost Yr 5 Errorbar

    ax.set_ylim(-50,height)
    ax.set_xlim(-width*4, len(loc) +(4*width))

    ax.set_xticks(loc + (2.5*width))

    ax.set_xticklabels(strat_names[1:], rotation='30', size='small', stretch='condensed',
                       ha='right' )

    ax.legend ((rect[0][0], rect[1][0], rect[2][0], rect[3][0], rect[4][0] ),
                ("TB Incidence", "MDR Incidence", "TB Mortality","Cost at Year 1", "Cost at Year 5"),loc='best',
                prop={'size':'8'})

    ax.set_title ("Side-by-Side Comparison of the Strategies Using 5 Key Metrics", {'fontweight':'bold'})
    ax.axhline(color='black')

    ax.set_ylabel('percentage change from baseline',{'fontweight':'bold'})

    fig.tight_layout()

    response=HttpResponse(content_type='image/png')
    canvas.print_png(response,facecolor=fig.get_facecolor())
    return response
开发者ID:JJPennington,项目名称:FlexDx-Xpert-Scale-Up,代码行数:95,代码来源:views.py

示例10: bargraph

# 需要导入模块: from matplotlib.figure import Figure [as 别名]
# 或者: from matplotlib.figure.Figure import get_facecolor [as 别名]
def bargraph(request):
    p = request.GET    

    try:
        d = [(float(p['d10']), float(p['d11']), float(p['d12']), float(p['d13']), float(p['d14'])),
             (float(p['d20']), float(p['d21']), float(p['d22']), float(p['d23']), float(p['d24'])),
             (float(p['d30']), float(p['d31']), float(p['d32']), float(p['d33']), float(p['d34'])),
             (float(p['d40']), float(p['d41']), float(p['d42']), float(p['d43']), float(p['d44'])),
             (float(p['d50']), float(p['d51']), float(p['d52']), float(p['d53']), float(p['d54'])),
             (float(p['d60']), float(p['d61']), float(p['d62']), float(p['d63']), float(p['d64'])),
             (float(p['d70']), float(p['d71']), float(p['d72']), float(p['d73']), float(p['d74'])),
             (float(p['d80']), float(p['d81']), float(p['d82']), float(p['d83']), float(p['d84']))]
    except:
        return render(request,"bad.html", { 'type':'bargraph' })
    
    s8name = strat_names[8]
    try:
        s8name = p['s8name']
    except:
        pass

    colors = ["grey","blue","green","yellow","red"]

    cdata = []

    for array in zip(*d): #Invert the numbers for proper display
        cdata.append([-1 * x for x in array])

    loc = np.arange(len(cdata[0]))
 
    width = 0.15

    fig = Figure(facecolor='white', dpi=150, figsize=(8,6))
    canvas = FigureCanvas(fig)

    ax = fig.add_subplot(111)

    rect = [ax.bar(loc+width*i, cdata[i], width, color=colors[i]) 
            for i in range(len(cdata))]
    
    max_height = max(chain(cdata[0],cdata[1],cdata[2],cdata[3],cdata[4])) + 10
    min_height = min(chain(cdata[0],cdata[1],cdata[2],cdata[3],cdata[4])) - 10

    print max_height, min_height

    ax.set_ylim(min_height,max_height)
    ax.set_xlim(-width*4, len(loc) +(4*width))

    ax.set_xticks(loc + (2.5*width))

    mod_strat_names = strat_names[1:-1] + ["8. {}".format(s8name)]

    ax.set_xticklabels(mod_strat_names, rotation='30', size='small', stretch='condensed',
                       ha='right' )

    ax.legend ((rect[0][0], rect[1][0], rect[2][0], rect[3][0], rect[4][0]),
                ("TB Incidence", "MDR Incidence", "TB Mortality","Cost at Year 1", "Cost at Year 5"),loc='best',
                prop={'size':'8'})

    ax.set_title ("Side-by-Side Comparison of the Strategies Using 5 Key Metrics", {'fontweight':'bold'})
    ax.axhline(color='black')

    ax.set_ylabel('percentage change from baseline',{'fontweight':'bold'})

    fig.tight_layout()

    response=HttpResponse(content_type='image/png')
    canvas.print_png(response,facecolor=fig.get_facecolor())
    return response
开发者ID:JJPennington,项目名称:FlexDx-Xpert-Scale-Up,代码行数:71,代码来源:views.py

示例11: dgraph4

# 需要导入模块: from matplotlib.figure import Figure [as 别名]
# 或者: from matplotlib.figure.Figure import get_facecolor [as 别名]

#.........这里部分代码省略.........
    try:
        which = int(p_val['ref'])
    except:
        pass
   
    if p_val['flag'] == 'E':
        try: 
            e2m = [float(p_val['e1%dm'%(x)]) for x in xrange(1,9)]
            e2c = [float(p_val['e1%dc'%(x)]) for x in xrange(1,9)]
        except:
            return render(request,"bad.html", { 'type':'uncert_e bargraph' })
    elif p_val['flag'] == 'P':
        try:
            p2m = [float(p_val['p1%dm'%(x)]) for x in xrange(1,9)]
            p2c = [float(p_val['p1%dc'%(x)]) for x in xrange(1,9)]
        except:
            return render(request,"bad.html", { 'type':'uncert_p bargraph' })
    elif p_val['flag'] == 'R':
        try:
            r2m = [float(p_val['r1%dm'%(x)]) for x in xrange(1,9)]
            r2c = [float(p_val['r1%dc'%(x)]) for x in xrange(1,9)]
        except:
            return render(request,"bad.html", { 'type':'uncert_r bargraph' })

    fig = Figure(facecolor='white', dpi=150)
    canvas = FigureCanvas(fig)

    ax = fig.add_subplot(111)

    ax.set_xlabel('% decrease in MDR-TB incidence at year 5 (more effective -->)',{'fontweight':'bold'})
    ax.set_ylabel('% increase in cost at year 5 (more costly -->)',{'fontweight':'bold'})
    ax.axvline(color='r')

    #n_colours = ['#fb9902','#fd5308','#fe2712','#a7194b','#8601af','#3d01a4','#0247fe','#0392ce','#66b032']

    n_colours = ['#000000','#e41a1c','#377eb8','#4daf4a','#984ea3','#ff7f00','#a65628','#f781bf','#999999']

    colours = ['#CC0000','#EC6002','#CC9999','#FFFF99','#CCFF00','#02C5F4','#0188A9','#006699','#2E014B']

    t_delta_y = 2
    t_delta_x = 0.25

    ax.text(0,0,'0')

    for i in xrange(8):
        ax.text(mdr[i]+t_delta_x,cmore[i]+t_delta_y,str(i+1))

    delta = 0.00002

    errorbars = []

    errorbars.append(ax.plot([0],[0],color='black', marker='*'));
    
    for i in xrange(8):
        centre_color = n_colours[i+1]
        if which-2 == i:
            centre_color = 'black'
        errorbars.append(ax.errorbar([mdr[i]],[cmore[i]],
                  xerr=[[mdr[i] - mdr_lo[i]],[mdr_hi[i] - mdr[i]]],
                  yerr=[[cmore[i] - c_lo[i]],[c_hi[i] - cmore[i]]],
                  color=centre_color,
                  ecolor=centre_color,
                  linewidth=2))
    ax.axhline(color='r') 
   
    ax.plot ([0],[0],marker='*',c='black',linestyle='None')    

    if p_val['flag'] == 'E':
        for x in range(8):
            ax.plot([e2m[x]],[e2c[x]],marker='o',c=n_colours[x+1],linestyle='None')
    elif p_val['flag'] == 'P':
        for x in range(8):
            ax.plot([p2m[x]],[p2c[x]],marker='o',c=n_colours[x+1],linestyle='None')
    elif p_val['flag'] == 'R':
        for x in range(8):
            ax.plot([r2m[x]],[r2c[x]],marker='o',c=n_colours[x+1],linestyle='None')

    ax.set_title("Change (%) in cost and MDR incidence at year 5",{'fontweight':'bold'})
 
    box = ax.get_position()
    ax.set_position([box.x0, box.y0-0.05, box.width, box.height+0.05])

    #ax.legend(errorbars,range(1,9),numpoints=1,bbox_to_anchor=(0.98,-0.08),ncol=9,columnspacing=1)
    fig.tight_layout()

    ax.legend ((errorbars[0][0],errorbars[1][0],errorbars[2][0],errorbars[3][0],errorbars[4][0],errorbars[5][0],errorbars[6][0],errorbars[7][0],errorbars[8][0]), 
               (strat_names[0],
                strat_names[1],
                strat_names[2],
                strat_names[3],
                strat_names[4],
                strat_names[5],
                strat_names[6],
                strat_names[7],
                strat_names[8]),
                loc='best', numpoints=1,prop={'size':'9'})

    response=HttpResponse(content_type='image/png')
    canvas.print_png(response,facecolor=fig.get_facecolor())
    return response
开发者ID:JJPennington,项目名称:FlexDx-Xpert-Scale-Up,代码行数:104,代码来源:views.py

示例12: dgraph2

# 需要导入模块: from matplotlib.figure import Figure [as 别名]
# 或者: from matplotlib.figure.Figure import get_facecolor [as 别名]
def dgraph2(request):
    p_val = request.GET

    try:
        cmore = [float(p_val['c{}'.format(x)]) for x in range(9)]
        mdr = [float(p_val['m{}'.format(x)]) for x in range(9)]
    except:
        return render(request,"bad.html",{ 'type':'dot graph 2' })
           
    which = -1
    try:
        which = int(p_val['ref'])
    except:
        pass

    s8name = strat_names[8]
    try:
        s8name = p_val['s8name']
    except:
        pass

    fig = Figure(facecolor='white', dpi=150)
    canvas = FigureCanvas(fig)

    ax2 = fig.add_subplot(111)

    ax2.set_xlabel('% decrease in MDR-TB incidence at year 5 (more effective -->)',{'fontweight':'bold'})
    ax2.set_ylabel('% increase in cost at year 5 (more costly -->)',{'fontweight':'bold'})

    points = [ ax2.plot(mdr[i],cmore[i],color='blue',marker='.',linestyle='None') for i in xrange(9) ]

    ax2.set_title("Change (%) in cost and MDR incidence at year 5",{'fontweight':'bold'})

    ax2.axhline(color='r')
    ax2.axvline(color='r')

    ax2.plot ([0],[0],marker='*',c='black',linestyle='None')


    point_list = []
    for i in xrange(9):
        dx,dy = placement(mdr[i],cmore[i],point_list,ax2)
        point_list.append([mdr[i],cmore[i],dx,dy])
        ref_color = '#000000'
        if i == which:
            ref_color = 'red'
        ax2.annotate(str(i), xy=(mdr[i],cmore[i]),
                     xytext=(mdr[i]+dx,cmore[i]+dy),
                     color=ref_color,
                     arrowprops=dict(color='red',arrowstyle="->"))    

    fig.tight_layout()

    ax2.legend ((points[0][0],points[1][0],points[2][0],points[3][0],points[4][0],points[5][0],points[6][0],points[7][0],points[8][0]), 
                (strat_names[0],
                 strat_names[1],
                 strat_names[2],
                 strat_names[3],
                 strat_names[4],
                 strat_names[5],
                 strat_names[6],
                 strat_names[7],
                 "8. {}".format(s8name)),
                 loc='best', numpoints=1,prop={'size':'9'})

    response=HttpResponse(content_type='image/png')
    canvas.print_png(response,facecolor=fig.get_facecolor())
    return response
开发者ID:JJPennington,项目名称:FlexDx-Xpert-Scale-Up,代码行数:70,代码来源:views.py

示例13: make_movie

# 需要导入模块: from matplotlib.figure import Figure [as 别名]
# 或者: from matplotlib.figure.Figure import get_facecolor [as 别名]

#.........这里部分代码省略.........

    # Construct an Aperture object for computing the PSF.  The Aperture object describes the
    # illumination pattern of the telescope pupil, and chooses good sampling size and resolution
    # for representing this pattern as an array.
    aper = galsim.Aperture(diam=args.diam, lam=args.lam, obscuration=args.obscuration,
                           nstruts=args.nstruts, strut_thick=args.strut_thick,
                           strut_angle=args.strut_angle*galsim.degrees,
                           screen_list=atm, pad_factor=args.pad_factor,
                           oversampling=args.oversampling)

    # Code to setup the Matplotlib animation.
    metadata = dict(title='Wavefront Movie', artist='Matplotlib')
    writer = anim.FFMpegWriter(fps=15, bitrate=5000, metadata=metadata)

    # For the animation code, we essentially draw a single figure first, and then use various
    # `set_XYZ` methods to update each successive frame.
    fig = Figure(facecolor='k', figsize=(11, 6))
    FigureCanvasAgg(fig)

    # Axis for the PSF image on the left.
    psf_ax = fig.add_axes([0.08, 0.15, 0.35, 0.7])
    psf_ax.set_xlabel("Arcsec")
    psf_ax.set_ylabel("Arcsec")
    psf_im = psf_ax.imshow(np.ones((128, 128), dtype=np.float64), animated=True,
                           vmin=0.0, vmax=args.psf_vmax, cmap='hot',
                           extent=np.r_[-1, 1, -1, 1]*0.5*args.psf_nx*args.psf_scale)

    # Axis for the wavefront image on the right.
    wf_ax = fig.add_axes([0.51, 0.15, 0.35, 0.7])
    wf_ax.set_xlabel("Meters")
    wf_ax.set_ylabel("Meters")
    wf_im = wf_ax.imshow(np.ones((128, 128), dtype=np.float64), animated=True,
                         vmin=-args.wf_vmax, vmax=args.wf_vmax, cmap='YlGnBu',
                         extent=np.r_[-1, 1, -1, 1]*0.5*aper.pupil_plane_size)
    cbar_ax = fig.add_axes([0.88, 0.175, 0.03, 0.65])
    cbar_ax.set_ylabel("Radians")
    fig.colorbar(wf_im, cax=cbar_ax)

    # Overlay an alpha-mask on the wavefront image showing which parts are actually illuminated.
    ilum = np.ma.masked_greater(aper.illuminated, 0.5)
    wf_ax.imshow(ilum, alpha=0.4, extent=np.r_[-1, 1, -1, 1]*0.5*aper.pupil_plane_size)

    # Color items white to show up on black background
    for ax in [psf_ax, wf_ax, cbar_ax]:
        for _, spine in ax.spines.items():
            spine.set_color('w')
        ax.title.set_color('w')
        ax.xaxis.label.set_color('w')
        ax.yaxis.label.set_color('w')
        ax.tick_params(axis='both', colors='w')

    etext = psf_ax.text(0.05, 0.92, '', transform=psf_ax.transAxes)
    etext.set_color('w')

    nstep = int(args.exptime / args.time_step)
    t0 = 0.0
    # Use astropy ProgressBar to keep track of progress and show an estimate for time to completion.
    with ProgressBar(nstep) as bar:
        with writer.saving(fig, args.outfile, 100):
            for i in range(nstep):
                # The wavefront() method accepts pupil plane coordinates `u` and `v` in meters, a
                # time `t` in seconds, and possibly a field angle `theta`.  It returns the wavefront
                # lag or lead in nanometers with respect to the "perfect" planar wavefront at the
                # specified location angle and time.  In normal use for computing atmospheric PSFs,
                # this is just an implementation detail.  In this script, however, we include the
                # wavefront in the visualization.
                wf = atm.wavefront(aper.u, aper.v, t0, theta=theta) * 2*np.pi/args.lam  # radians
                # To make an actual PSF GSObject, we use the makePSF() method, including arguments
                # for the wavelength `lam`, the field angle `theta`, the aperture `aper`, the
                # starting time t0, and the exposure time `exptime`.  Here, since we're making a
                # movie, we set the exptime equal to just a single timestep, though normally we'd
                # want to set this to the full exposure time.
                psf = atm.makePSF(lam=args.lam, theta=theta, aper=aper,
                                  t0=t0, exptime=args.time_step)
                # `psf` is now just like an any other GSObject, ready to be convolved, drawn, or
                # transformed.  Here, we just draw it into an image to add to our movie.
                psf_img0 = psf.drawImage(nx=args.psf_nx, ny=args.psf_nx, scale=args.psf_scale)

                if args.accumulate:
                    psf_img_sum += psf_img0
                    psf_img = psf_img_sum/(i+1)
                else:
                    psf_img = psf_img0

                # Calculate simple estimate of size and ellipticity
                e = galsim.utilities.unweighted_shape(psf_img)

                # Update t0 for the next movie frame.
                t0 += args.time_step

                # Matplotlib code updating plot elements
                wf_im.set_array(wf)
                wf_ax.set_title("t={:5.2f} s".format(i*args.time_step))
                psf_im.set_array(psf_img.array)
                etext.set_text("$e_1$={:6.3f}, $e_2$={:6.3f}, $r^2$={:6.3f}".format(
                        e['e1'], e['e2'], e['rsqr']*args.psf_scale**2))
                with warnings.catch_warnings():
                    warnings.simplefilter("ignore")
                    writer.grab_frame(facecolor=fig.get_facecolor())
                bar.update()
开发者ID:GalSim-developers,项目名称:GalSim,代码行数:104,代码来源:psf_wf_movie.py

示例14: Frequency

# 需要导入模块: from matplotlib.figure import Figure [as 别名]
# 或者: from matplotlib.figure.Figure import get_facecolor [as 别名]

#.........这里部分代码省略.........
        if self.number_of_subplots > 1:
            self.cb_ax = self.fig.add_axes(self.get_cb_axes())
        else:
            divider = make_axes_locatable(ax)
            self.cb_ax = divider.append_axes("right", size="5%", pad=0.05)

        self.fig.colorbar(im, cax=self.cb_ax,
                    orientation='vertical',
                    ticks=self.image_defs['y_labels'],
                    format = FuncFormatter(eval('self.'+self.image_defs['formatter'])))

        #print self.image_defs['y_labels']
        for t in self.cb_ax.get_yticklabels():
            t.set_fontsize(colorbar_fontsize)

        #self.fig.tight_layout()
        canvas = FigureCanvas(self.fig)
        self.fig.canvas.mpl_connect('draw_event', self.on_draw)
        canvas.show()

        if save_file :
            self.save_plot(canvas, save_file)

        #todo this ought to a command line param
        if not self.run_quietly:
            dia = VOAPlotWindow('pythonProp - ' + self.image_defs['title'], canvas, parent=parent, datadir=self.datadir)
        return

    def on_draw(self, event):
        top = self.fig.subplotpars.top
        bottom = self.fig.subplotpars.bottom
        hspace = self.fig.subplotpars.hspace
        wspace = self.fig.subplotpars.wspace

        fig_height = self.fig.get_figheight()

        needs_adjusting = False

        # Area required at the top of the plot (Main title and subplot title)
        bbox = self.subplot_title_label.get_window_extent()
        subplot_title_bbox = bbox.inverse_transformed(self.fig.transFigure)

        bbox = self.main_title_label.get_window_extent()
        main_title_bbox = bbox.inverse_transformed(self.fig.transFigure)

        _preferred_top_space = 1.25*(subplot_title_bbox.height + main_title_bbox.height)
        _actual_top_space = 1-top

        if (_actual_top_space < _preferred_top_space) or ((_actual_top_space - _preferred_top_space)>0.11):
            top = 0.99 - _preferred_top_space
            needs_adjusting = True

        if needs_adjusting:
            self.fig.subplots_adjust(top = top, bottom = bottom, hspace = hspace, wspace = wspace)
            self.cb_ax.set_position(self.get_cb_axes())
            self.fig.canvas.draw()
        return False


    def save_plot(self, canvas, filename=None):
        canvas.print_figure(filename, dpi=self.dpi, facecolor=self.fig.get_facecolor(), edgecolor='none')


    def get_cb_axes(self):
        bbox = self.subplots[0].get_window_extent()
        axis_upper_y = bbox.inverse_transformed(self.fig.transFigure).ymax
        bbox = self.subplots[-1].get_window_extent()
        axis_lower_y = bbox.inverse_transformed(self.fig.transFigure).ymin
        return [0.87, axis_lower_y, 0.02, axis_upper_y-axis_lower_y]


    def percent_format(self, x, pos):
        return '%(percent)3d%%' % {'percent':x*100}

    def SNR_format(self, x, pos):
        return '%3ddB' % x

    def SDBW_format(self, x, pos):
        return '%3ddBW' % x

    """
    The values below are derived from material
    presented at http://www.voacap.com/s-meter.html
    """
    def SMETER_format(self, x, pos):
        S_DICT = {-151.18:'S1', -145.15:'S2', -139.13:'S3', -133.11:'S4', -127.09:'S5', \
                    -121.07:'S6', -115.05:'S7', -109.03:'S8', -103.01:'S9', -93.01:'S9+10dB', \
                    -83.01:'S9+20dB', -73.01:'S9+30dB', -63.01:'S9+40dB', -53.01:'S9+50dB', -43.01:'S9+60dB'}
        if x in S_DICT:
        	return '%s' % S_DICT[x]
            #return _('%(value)ddBW (%(s_value)s)') %{'value':x, 's_value':S_DICT[x]}
        else : return '%3d' % x


    def frequency_format(self, x, pos):
        return '%2dMHz' % x


    def default_format(self, x, pos):
        return '%d' % x
开发者ID:jawatson,项目名称:pythonprop,代码行数:104,代码来源:voaAreaPlot.py


注:本文中的matplotlib.figure.Figure.get_facecolor方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。