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


Python Figure.clf方法代码示例

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


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

示例1: get_canvas_and_axes

# 需要导入模块: from matplotlib.figure import Figure [as 别名]
# 或者: from matplotlib.figure.Figure import clf [as 别名]
def get_canvas_and_axes():
    'It returns a matplotlib canvas and axes instance'
    fig = Figure()
    fig.clf()
    canvas = FigureCanvas(fig)
    axes = fig.add_subplot(111)
    return canvas, axes, fig
开发者ID:pziarsolo,项目名称:goldenbraid,代码行数:9,代码来源:excel.py

示例2: PlotCanvas

# 需要导入模块: from matplotlib.figure import Figure [as 别名]
# 或者: from matplotlib.figure.Figure import clf [as 别名]
class PlotCanvas(wx.Panel, Observable):
    def __init__(self, parent, subplots):
        wx.Panel.__init__(self, parent, -1, style=wx.SIMPLE_BORDER)
        Observable.__init__(self)

        self.fig = Figure()
        self.canvas = FigCanvas(self, -1, self.fig)
        self.toolbar = NavigationToolbar2Wx(self.canvas)
        self.toolbar.Realize()

        self.initialize_subplots(subplots)

        self.sizer = wx.BoxSizer(wx.VERTICAL)
        self.sizer.Add(self.toolbar, 1, wx.GROW | wx.CENTER)
        self.sizer.Add(self.canvas, 30, wx.GROW)

        self.SetSizer(self.sizer)

    def initialize_subplots(self, subplots):
        self.sub_data_plots = subplots

        for plot in self.sub_data_plots:
            plot.initialize_figure(self.fig)

    def draw(self):
        for plot in self.sub_data_plots:
            plot.prepare_plot_for_draw()
        self.canvas.draw()

    def update_subplots(self, subplots):
        self.fig.clf()
        self.initialize_subplots(subplots)
        self.canvas.draw()
开发者ID:pobed2,项目名称:SupermileageBench,代码行数:35,代码来源:plot_canvas.py

示例3: PlotCanvas

# 需要导入模块: from matplotlib.figure import Figure [as 别名]
# 或者: from matplotlib.figure.Figure import clf [as 别名]
class PlotCanvas(FigureCanvas):
    """Ultimately, this is a QWidget (as well as a FigureCanvasAgg, etc.)."""
    def __init__(self):
        self.fig = Figure()
        super(PlotCanvas, self).__init__(self.fig)
        self.axes1 = None
        self.axes1b = None
        self.axes2 = None
        self.axes2b = None
        self.init_axes()
        self.placeholder()

    def placeholder(self):
        t__ = np.arange(0.0, 3.0, 0.01)
        s__ = np.sin(2*np.pi*t__)
        self.axes1.plot(t__, s__, 'b-')
        self.axes2.plot(t__, s__, 'r-')
        self.axes1.grid(True, which="both", color="0.65", ls='-')
        self.axes2.grid(True, which="both", color="0.65", ls='-')
        self.axes1.set_xscale('log')
        self.axes1.set_xlim(right=3)
        self.axes2.set_title("Scimpy Speaker Designer!")

    def init_axes(self):
        self.axes1 = self.fig.add_subplot(211)
        self.axes2 = self.fig.add_subplot(212)
        self.axes1b = matplotlib.axes.Axes.twinx(self.axes1)
        self.axes2b = matplotlib.axes.Axes.twinx(self.axes2)

    def clear_axes(self):
        if self.parentWidget().holdplotaction.isChecked() == False:
            self.fig.clf()
            self.init_axes()
开发者ID:maqifrnswa,项目名称:scimpy,代码行数:35,代码来源:centralplotui.py

示例4: plotwo

# 需要导入模块: from matplotlib.figure import Figure [as 别名]
# 或者: from matplotlib.figure.Figure import clf [as 别名]
def plotwo(e,idata,fig=None,mode='pd',clean=True,ang=75):
    '''you can plot according to 'mode':
    pd: psi/delta
    pd-tc: tan(psi),cos(delta)
    eps: dielectric function
    nk: refractive indices
    '''
    from numpy import sqrt,iterable
    if fig==None:
        from matplotlib.figure import Figure
        fig=Figure()
    elif clean: fig.clf()
    from matplotlib.pyplot import subplot
    if iterable(idata[0]): data=idata[0]+1j*idata[1]
    else: data=idata
    if mode[:2]!='pd':data=from_ellips(data.real,data.imag,ang=ang,unit='deg')
    if mode=='nk':data=sqrt(data)
    if mode=='pd_ct':
        from numpy import tan,cos
        data=tan(data.real*pi/180)+1j*cos(data.imag*pi/180)
    for j in range(2):
        axa=subplot(2,1,j+1)
        if clean:
            axa.set_xlabel('energy [eV]')
            if mode=='nk':axa.set_ylabel(['n','k'][j])
            elif mode=='eps':axa.set_ylabel('$\epsilon$ '+['real','imag'][j])
            elif mode=='pd_ct': axa.set_ylabel(['tan $\Psi$','cos $\Delta$'][j])
            elif mode=='pd': axa.set_ylabel(['$\Psi$','$\Delta$'][j])
        if j==0:axa.plot(e,data.real)
        else:axa.plot(e,data.imag)
开发者ID:limu007,项目名称:Charlay,代码行数:32,代码来源:profit.py

示例5: MatplotlibCanvas

# 需要导入模块: from matplotlib.figure import Figure [as 别名]
# 或者: from matplotlib.figure.Figure import clf [as 别名]
class MatplotlibCanvas(FigureCanvas):

    def __init__(self, parent=None, width=5, height=4, dpi=100):

        self.figure = Figure(figsize=(width, height), dpi=dpi)
        super(MatplotlibCanvas, self).__init__(self.figure)

        self.reset()
        self.setParent(parent)
        super(MatplotlibCanvas, self).setSizePolicy(
            QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Expanding
            )
        super(MatplotlibCanvas, self).updateGeometry()

    def reset(self):

        self.figure.clf()
        self.change_layout('1x1')
        self.figure.canvas.draw()

    def change_layout(self, new_layout_string, active_index=1):

        self.figure.clf()
        self.figure_layout = [int(x) for x in new_layout_string.split('x')]
        self.layoutSize = self.figure_layout[0] * self.figure_layout[1]
        self.axes = self.figure.add_subplot(
            self.figure_layout[0], self.figure_layout[1], active_index
            )
        self.figure.canvas.draw()

    def select_subfigure(self, index):

        self.axes = self.figure.add_subplot(
            self.figure_layout[0], self.figure_layout[1], index
            )
开发者ID:scummos,项目名称:pyfitsviewer,代码行数:37,代码来源:fitsviewer.py

示例6: HistogramEquityWinLoss

# 需要导入模块: from matplotlib.figure import Figure [as 别名]
# 或者: from matplotlib.figure.Figure import clf [as 别名]
class HistogramEquityWinLoss(FigureCanvas):
    def __init__(self, ui):
        self.ui = proxy(ui)
        self.fig = Figure(dpi=50)
        super(HistogramEquityWinLoss, self).__init__(self.fig)
        # self.drawfigure(template,game_stage,decision)
        self.ui.horizontalLayout_3.insertWidget(1, self)

    def drawfigure(self, p_name, game_stage, decision, l):
        data = l.get_histrogram_data('Template', p_name, game_stage, decision)
        wins = data[0]
        losses = data[1]
        bins = np.linspace(0, 1, 50)

        self.fig.clf()
        self.axes = self.fig.add_subplot(111)  # create an axis
        self.axes.hold(True)  # discards the old graph
        self.axes.set_title('Histogram')
        self.axes.set_xlabel('Equity')
        self.axes.set_ylabel('Number of hands')

        self.axes.hist(wins, bins, alpha=0.5, label='wins', color='g')
        self.axes.hist(losses, bins, alpha=0.5, label='losses', color='r')
        self.axes.legend(loc='upper right')
        self.draw()
开发者ID:vidmantasb,项目名称:Poker,代码行数:27,代码来源:gui_qt_logic.py

示例7: PlotOverview

# 需要导入模块: from matplotlib.figure import Figure [as 别名]
# 或者: from matplotlib.figure.Figure import clf [as 别名]
class PlotOverview(qtgui.QWidget):
    def __init__(self, db):
        self.db = db
        self.fig = Figure()
        self.canvas = FigureCanvas(self.fig)
        super().__init__()

        lay_v = qtgui.QVBoxLayout()
        self.setLayout(lay_v)

        self.year = qtgui.QComboBox()
        self.year.currentIndexChanged.connect(self.plot)

        lay_h = qtgui.QHBoxLayout()
        lay_h.addWidget(self.year)
        lay_h.addStretch(1)
        lay_v.addLayout(lay_h)
        lay_v.addWidget(self.canvas)

        self.update()

    def update(self):
        constraints = self.db.get_constraints()
        current_year = self.year.currentText()
        self.year.clear()
        years = [y for y in range(min(constraints['start_date']).year, datetime.datetime.now().year + 1)]
        self.year.addItems([str(y) for y in years])
        try:
            self.year.setCurrentIndex(years.index(current_year))
        except ValueError:
            self.year.setCurrentIndex(len(years) - 1)

    def plot(self):
        self.fig.clf()
        ax = self.fig.add_subplot(111)

        worked = np.zeros((12, 34)) + np.nan

        year = int(self.year.currentText())
        for month in range(12):
            for day in range(calendar.monthrange(year, month + 1)[1]):
                date = datetime.date(year, month + 1, day + 1)
                if date < datetime.datetime.now().date():
                    t = self.db.get_worktime(date).total_seconds() / 60.0 - self.db.get_desiredtime(date)
                    worked[month, day] = t
                    ax.text(day, month, re.sub('0(?=[.])', '', ('{:.1f}'.format(t / 60))), ha='center', va='center')

        worked[:, 32:] = np.nansum(worked[:, :31], axis=1, keepdims=True)

        for month in range(12):
            ax.text(32.5, month, re.sub('0(?=[.])', '', ('{:.1f}'.format(worked[month, -1] / 60))), ha='center', va='center')

        ax.imshow(worked, vmin=-12*60, vmax=12*60, interpolation='none', cmap='coolwarm')
        ax.set_xticks(np.arange(31))
        ax.set_yticks(np.arange(12))
        ax.set_xticklabels(1 + np.arange(31))
        ax.set_yticklabels(calendar.month_name[1:])

        self.fig.tight_layout()
        self.canvas.draw()
开发者ID:mbillingr,项目名称:timetracker,代码行数:62,代码来源:statisticsdialog.py

示例8: MatplotlibWidget

# 需要导入模块: from matplotlib.figure import Figure [as 别名]
# 或者: from matplotlib.figure.Figure import clf [as 别名]
class MatplotlibWidget(FigureCanvas):

	def __init__(self, parent=None, width=5, height=4, dpi=100):

		super(MatplotlibWidget, self).__init__(Figure())

#		self.setWindowFlags(QtCore.Qt.WindowStaysOnTopHint)
		self.setParent(parent)
		self.figure = Figure(figsize=(width, height), dpi=dpi) 
		self.canvas = FigureCanvas(self.figure)

#		FigureCanvas.setSizePolicy(self,
#				QtGui.QSizePolicy.Expanding,
#				QtGui.QSizePolicy.Expanding)

		FigureCanvas.updateGeometry(self)
		self.axes = self.figure.add_subplot(111)
		self.setMinimumSize(self.size()*0.3)

		print("---------------------- done")




	def subplot(self,label='111'):
		self.axes=self.figure.add_subplot(label)

	def plot(self,*args,**args2):
		self.axes.plot(*args,**args2)
		self.draw()

	def clf(self):
		self.figure.clf()
开发者ID:microelly2,项目名称:reconstruction,代码行数:35,代码来源:mpl.py

示例9: plot

# 需要导入模块: from matplotlib.figure import Figure [as 别名]
# 或者: from matplotlib.figure.Figure import clf [as 别名]
def plot():
    fig = Figure()
    i = 0
    while True:
        print i,report_memory(i)
        fig.clf()
        ax = fig.add_axes([0.1,0.1,0.7,0.7])
        ax.plot([1,2,3])
        i += 1
开发者ID:AlexSzatmary,项目名称:matplotlib,代码行数:11,代码来源:memleak_nongui.py

示例10: plotwidget

# 需要导入模块: from matplotlib.figure import Figure [as 别名]
# 或者: from matplotlib.figure.Figure import clf [as 别名]
class plotwidget(FigureCanvas):
    def __init__(self, parent, width=12, height=6, dpi=72, projection3d=False):

        #plotdata can be 2d array for image plot or list of 2 1d arrays for x-y plot or 2d array for image plot or list of lists of 2 1D arrays
        self.projection3d=projection3d
        self.fig=Figure(figsize=(width, height), dpi=dpi)
        if projection3d:
            self.axes=self.fig.add_subplot(111, navigate=True, projection='3d')
        else:
            self.axes=self.fig.add_subplot(111, navigate=True)

        self.axes.hold(True)
        FigureCanvas.__init__(self, self.fig)
        self.setParent(parent)
        #self.parent=parent
        FigureCanvas.setSizePolicy(self, QSizePolicy.Expanding, QSizePolicy.Expanding)
        FigureCanvas.updateGeometry(self)
        #NavigationToolbar(self, parent)
        NavigationToolbar(self, self)

        self.mpl_connect('button_press_event', self.myclick)
        self.clicklist=[]
        self.cbax=None
    
    def redoaxes(self, projection3d=False, onlyifprojectionchanges=True, cbaxkwargs={}):
        if onlyifprojectionchanges and (projection3d==self.projection3d):
            return
        self.fig.clf()
        if projection3d:
            self.axes=self.fig.add_subplot(111, navigate=True, projection='3d')
            self.axes.set_axis_off()
        else:
            self.axes=self.fig.add_subplot(111, navigate=True)
        if not self.cbax is None or len(cbaxkwargs)>0:
            self.createcbax(**cbaxkwargs)

        self.axes.hold(True)
    
    def createcbax(self, axrect=[0.88, 0.1, 0.04, 0.8], left=0, rshift=.01):

        self.fig.subplots_adjust(left=left, right=axrect[0]-rshift)
        self.cbax=self.fig.add_axes(axrect)

        
    def myclick(self, event):
        if not (event.xdata is None or event.ydata is None):
            arrayxy=[event.xdata, event.ydata]
            print 'clicked on image: array indeces ', arrayxy, ' using button', event.button
            self.clicklist+=[arrayxy]
            self.emit(SIGNAL("genericclickonplot"), [event.xdata, event.ydata, event.button, event.inaxes])
开发者ID:johnmgregoire,项目名称:JCAPDataProcess,代码行数:52,代码来源:fcns_compplots.py

示例11: Plotter

# 需要导入模块: from matplotlib.figure import Figure [as 别名]
# 或者: from matplotlib.figure.Figure import clf [as 别名]
class Plotter(FigureCanvas):

    def __init__(self, parent=None):
        dpi = 100
        self.plot_options = {"linewidth":3,"color":"k"}
        self.plot_options_axes = {"linewidth":2, "color":'0.7'} #,'alpha':0.7}
        self.fig = Figure(figsize=(16,9), dpi=dpi)
        
        # x=np.arange(-10,10,0.1)
        # y=np.sin(x)
        # self.make_graph(x,y)

        FigureCanvas.__init__(self, self.fig)
        self.setParent(parent)

        FigureCanvas.setSizePolicy(self,
                                   QtGui.QSizePolicy.Expanding,
                                   QtGui.QSizePolicy.Expanding)
        FigureCanvas.updateGeometry(self)
    
    def save(self):
        self.fig.savefig('plot.png')    

    def make_graph(self, x, y,*args):
        """
        This just makes a very simple plot.
        """
        # try:
        #     a = args[0]
        # except IndexError:
        #     a = 1.0
        # y = a*y
        self.fig.clf()
        ax1 = self.fig.add_subplot(111)
        # ax1.hold(False)
        x_space = np.absolute(x[0] - x[1])
        y_max, y_min = np.amax(y), np.amin(y)
        y_space = np.absolute(y_max - y_min)
        ax1.set_xlim((x[0]-5.0*x_space,x[-1]+5.0*x_space))
        ax1.set_ylim([y_min-0.25*y_space, y_max+0.25*y_space])
        ax1.grid()
        ax1.set_xlabel(r"$x$")
        ax1.set_ylabel(r"$f(x)$")
        # ax1.set_title(r"Graph of $f(x)$")
        x_axis = np.linspace(x[0]-5.0*x_space,x[-1]+5.0*x_space,x.size)
        ax1.plot(x_axis, np.zeros(x.size), **self.plot_options_axes)
        ax1.plot(np.zeros(x.size), np.linspace(y_min-0.25*y_space, y_max+0.25*y_space,x.size),**self.plot_options_axes)
        ax1.plot(x, y, **self.plot_options)
开发者ID:dean-shaff,项目名称:plotface,代码行数:50,代码来源:plotter.py

示例12: PiePlotter

# 需要导入模块: from matplotlib.figure import Figure [as 别名]
# 或者: from matplotlib.figure.Figure import clf [as 别名]
class PiePlotter(FigureCanvas):
    def __init__(self, ui, winnerCardTypeList):
        self.ui = proxy(ui)
        self.fig = Figure(dpi=50)
        super(PiePlotter, self).__init__(self.fig)
        # self.drawfigure(winnerCardTypeList)
        self.ui.vLayout4.insertWidget(1, self)

    def drawfigure(self, winnerCardTypeList):
        self.fig.clf()
        self.axes = self.fig.add_subplot(111)  # create an axis
        self.axes.hold(False)
        self.axes.pie([float(v) for v in winnerCardTypeList.values()],
                      labels=[k for k in winnerCardTypeList.keys()], autopct=None)
        self.axes.set_title('Winning probabilities')
        self.draw()
开发者ID:vidmantasb,项目名称:Poker,代码行数:18,代码来源:gui_qt_logic.py

示例13: plot

# 需要导入模块: from matplotlib.figure import Figure [as 别名]
# 或者: from matplotlib.figure.Figure import clf [as 别名]
def plot(request, image_format):
    plot_filepath = os.path.join(settings.CACHE_ROOT, "kicker", "kicker." + image_format)
    try:
        timestamps = [models.KickerNumber.objects.latest().timestamp]
    except models.KickerNumber.DoesNotExist:
        timestamps = []
    if is_update_necessary(plot_filepath, timestamps=timestamps):
        eligible_players = [entry[0] for entry in get_eligible_players()]
        hundred_days_ago = datetime.datetime.now() - datetime.timedelta(days=100)
        plot_data = []
        for player in eligible_players:
            x_values, y_values = [], []
            latest_day = None
            kicker_numbers = list(models.KickerNumber.objects.filter(player=player, timestamp__gt=hundred_days_ago))
            for i, kicker_number in enumerate(kicker_numbers):
                if i == len(kicker_numbers) - 1 or \
                        kicker_numbers[i + 1].timestamp.toordinal() != kicker_number.timestamp.toordinal():
                    x_values.append(kicker_number.timestamp)
                    y_values.append(kicker_number.number)
            plot_data.append((x_values, y_values, player.kicker_user_details.nickname or player.username))
        if image_format == "png":
            figsize, position, legend_loc, legend_bbox, ncol = (8, 12), (0.1, 0.5, 0.8, 0.45), "upper center", [0.5, -0.1], 3
        else:
            figsize, position, legend_loc, legend_bbox, ncol = (10, 7), (0.1, 0.1, 0.6, 0.8), "best", [1, 1], 1
        figure = Figure(frameon=False, figsize=figsize)
        canvas = FigureCanvasAgg(figure)
        axes = figure.add_subplot(111)
        axes.set_position(position)
        for line in plot_data:
            if len(line[0]) == 1:
                line[0].append(line[0][0] - datetime.timedelta(days=1))
                line[1].append(line[1][0])
            axes.plot(line[0], line[1], label=line[2], linewidth=2)
        months_locator = matplotlib.dates.MonthLocator()
        axes.xaxis.set_major_locator(months_locator)
        months_formatter = matplotlib.dates.DateFormatter('%b')
        axes.xaxis.set_major_formatter(months_formatter)
        axes.grid(True)
        axes.legend(loc=legend_loc, bbox_to_anchor=legend_bbox, ncol=ncol, shadow=True)
        mkdirs(plot_filepath)
        canvas.print_figure(plot_filepath)
        figure.clf()
        storage_changed.send(models.KickerNumber)
    if not os.path.exists(plot_filepath):
        raise Http404("No kicker data available.")
    return static_file_response(plot_filepath, "kicker.pdf" if image_format == "pdf" else None)
开发者ID:msincan,项目名称:juliabase,代码行数:48,代码来源:views.py

示例14: ExporterBackend

# 需要导入模块: from matplotlib.figure import Figure [as 别名]
# 或者: from matplotlib.figure.Figure import clf [as 别名]
class ExporterBackend(Backend):
    def __init__(self, model, file_format):
        super(ExporterBackend, self).__init__(model)
        self._figure = Figure()
        self._file_format = file_format

    def render(self, filename_base):
        FigureCanvasAgg(self._figure)
        for i, plot in enumerate(self._model.get_plots()):
            self._figure.clf()
            backend = InteractiveBackend(self._model, self._figure)
            title = plot.get_title()
            if title == '':
                title = 'unnamed_plot_' + str(i)
            filename = '{}_{}.{}'.format(
                filename_base, title, self._file_format)
            backend.render(filename, i)
            self._figure.savefig(filename)
开发者ID:SharpLu,项目名称:Sympathy-for-data-benchmark,代码行数:20,代码来源:backend.py

示例15: ScatterPlot

# 需要导入模块: from matplotlib.figure import Figure [as 别名]
# 或者: from matplotlib.figure.Figure import clf [as 别名]
class ScatterPlot(FigureCanvas):
    def __init__(self, ui):
        self.ui = proxy(ui)
        self.fig = Figure()
        super(ScatterPlot, self).__init__(self.fig)
        self.ui.horizontalLayout_4.insertWidget(1, self)

    def drawfigure(self, p_name, game_stage, decision, l, smallBlind, bigBlind, maxValue, minEquityBet, max_X,
                   maxEquityBet,
                   power):
        wins, losses = l.get_scatterplot_data('Template', p_name, game_stage, decision)
        self.fig.clf()
        self.axes = self.fig.add_subplot(111)  # create an axis
        self.axes.hold(True)
        self.axes.set_title('Wins and Losses')
        self.axes.set_xlabel('Equity')
        self.axes.set_ylabel('Minimum required call')

        try:
            self.axes.set_ylim(0, max(wins['minCall'].tolist() + losses['minCall'].tolist()) * 1.1)
        except:
            self.axes.set_ylim(0, 1)
        self.axes.set_xlim(0, 1)

        # self.axes.set_xlim(.5, .8)
        # self.axes.set_ylim(0, .2)

        area = np.pi * (50 * wins['FinalFundsChange'])  # 0 to 15 point radiuses
        green_dots = self.axes.scatter(x=wins['equity'].tolist(), y=wins['minCall'], s=area, c='green', alpha=0.5)

        area = np.pi * (50 * abs(losses['FinalFundsChange']))
        red_dots = self.axes.scatter(x=losses['equity'].tolist(), y=losses['minCall'], s=area, c='red', alpha=0.5)

        self.axes.legend((green_dots, red_dots),
                         ('Wins', 'Losses'), loc=2)

        x2 = np.linspace(0, 1, 100)
        d2 = Curvefitting(x2, 0, 0, maxValue, minEquityBet, maxEquityBet, max_X, power)
        self.line3, = self.axes.plot(np.arange(0, 1, 0.01), d2.y[-100:],
                                     'r-')  # Returns a tuple of line objects, thus the comma

        self.axes.grid()
        self.draw()
开发者ID:vidmantasb,项目名称:Poker,代码行数:45,代码来源:gui_qt_logic.py


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