本文整理汇总了Python中matplotlib.figure.Figure.legend方法的典型用法代码示例。如果您正苦于以下问题:Python Figure.legend方法的具体用法?Python Figure.legend怎么用?Python Figure.legend使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类matplotlib.figure.Figure
的用法示例。
在下文中一共展示了Figure.legend方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: MatplotlibWidget
# 需要导入模块: from matplotlib.figure import Figure [as 别名]
# 或者: from matplotlib.figure.Figure import legend [as 别名]
class MatplotlibWidget(FigureCanvas):
def __init__(self, parent=None):
super(MatplotlibWidget, self).__init__(Figure())
#self.hide()
self.setParent(parent)
self.figure = Figure()
self.canvas = FigureCanvas(self.figure)
self.ax = self.figure.add_subplot(111)
self.ax.yaxis.grid(color='gray', linestyle='dashed')
def add_plot_line(self, x, y):
self.ax.plot(x, y, 'r')
def add_legend(self, list):
#list of strings like "X1 = blaghlbah"
self.figure.legend([x for x in list], loc='upper left')
def draw_graph(self):
self.figure.draw()
def show_graph(self):
self.figure.show()
def plot_bar_graph(self):
pass
示例2: save_plot
# 需要导入模块: from matplotlib.figure import Figure [as 别名]
# 或者: from matplotlib.figure.Figure import legend [as 别名]
def save_plot(fname, plot_name, plot):
from matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas
from matplotlib.figure import Figure
from matplotlib.dates import DateFormatter
fig = Figure()
ax = fig.add_subplot(111)
ax.xaxis.set_major_formatter(DateFormatter('%H:%M'))
ax.set_xlabel("Time")
ax.set_ylabel(plot_name)
fig.set_figheight(20)
fig.set_figwidth(30)
fig.autofmt_xdate()
handles = []
labels = []
for graph in plot:
x, y = plot[graph]
handles.append(ax.plot(x, y))
labels.append(graph)
fig.legend(handles, labels, 1, shadow=True)
canvas = FigureCanvas(fig)
canvas.print_figure(fname, dpi=80)
示例3: make_fig
# 需要导入模块: from matplotlib.figure import Figure [as 别名]
# 或者: from matplotlib.figure.Figure import legend [as 别名]
def make_fig(self, start_time, end_time):
fig = Figure(figsize=(8,8), dpi=72)
self.lines = []
N = len(self.channels)
self.ax = fig.add_subplot(1,1,1) #new singleplot configuration
colordict = ['#A6D1FF','green','red','cyan','magenta','yellow','white']
minx = 0
maxx = 0
graph = []
for i, channel in enumerate(self.channels):
#subplot syntax is numrows, numcolumns, subplot ID
print "ArrayMapper.make_fig(): self.X is is " , self.X, type(self.X), len(self.X)
print "ArrayMapper.make_fig(): channel is ", channel
print "ArrayMapper.make_fig(): self.numSamples=", self.numSamples
time_range = arange(self.numSamples)
#print "start_time= ", start_time, "end_time =", end_time
if ((start_time != None) & (end_time != None)):
time_range = arange(start_time, end_time, (end_time - start_time)/self.numSamples)
#print "time_range is ", time_range
x = self.X[channel-1,:]
if minx > min(x):
minx = copy.deepcopy(min(x))
if maxx < max(x):
maxx = copy.deepcopy(max(x))
color = colordict[((i-1)%7)]
newp = self.ax.plot(time_range, x, color, label=("channel " + str(i+1)))
newp[0].set_linewidth(4)
graph.append(newp)
self.ax.set_xlabel('index')
self.ax.set_title('Evoked response')
#self.ax.legend()
fig.legend(graph,self.channels,'upper right')
if ((start_time != None) & (end_time != None)):
mid = start_time + (end_time - start_time)/2.0
else:
mid = self.numSamples/2.0
#print "setting up line at (([%d, %d], [%d, %d])[0]" % (mid, mid, min(x), max(x))
LO = self.view3.newLength/2
#line = self.ax.plot([mid, mid], [minx, maxx],'w')[0]
#left edge of window:
line = self.ax.plot([mid-LO, mid-LO], [minx, maxx],'y')[0]
self.ax.add_line(line)
self.lines.append(line)
#middle of window, where the scalar data comes from:
line = self.ax.plot([mid, mid], [minx, maxx],'r')[0]
self.ax.add_line(line)
self.lines.append(line)
#right edge of window
line = self.ax.plot([mid+LO, mid+LO], [minx, maxx],'y')[0]
self.ax.add_line(line)
self.lines.append(line)
self.ax.patch.set_facecolor('black') #transparency
self.finishedFigure = fig
return fig
示例4: generate_figure
# 需要导入模块: from matplotlib.figure import Figure [as 别名]
# 或者: from matplotlib.figure.Figure import legend [as 别名]
def generate_figure(samples):
ohms_styles = (
('r', 'r:'),
('x', 'y:'),
('z', 'g:'),
)
x = []
yswr = []
handles = []
for sample in samples:
x.append(float(sample['frequency'])/10**6)
yswr.append(sample['swr'])
fake_file = StringIO()
figure = Figure(figsize=(9, 6, ), facecolor='white')
canvas = FigureCanvasAgg(figure)
axis = figure.add_subplot(111)
axis.set_ylabel('SWR')
axis.set_xlabel('Frequency (MHz)')
axis.set_axis_bgcolor((1, 1, 1,))
axis_ohms = axis.twinx()
axis_ohms.set_ylabel('Ohms')
handles.append(
axis.plot(x, yswr, 'b', label='SWR')[0]
)
for prop, style in ohms_styles:
sample = [float(v.get(prop)) for v in samples]
handles.append(
axis_ohms.plot(x, sample, style, label=prop)[0]
)
figure.legend(
handles=handles,
labels=[
'SWR'
] + [prop for prop, style in ohms_styles]
)
canvas.print_png(fake_file)
data = fake_file.getvalue()
return data
示例5: CreateCurrentVoltagePlot
# 需要导入模块: from matplotlib.figure import Figure [as 别名]
# 或者: from matplotlib.figure.Figure import legend [as 别名]
def CreateCurrentVoltagePlot(t, c, v, title, filename, xlim=(0,60)):
figure = Figure(figsize=(8,4))
figure.suptitle(title)
axis1 = figure.add_subplot(111)
axis1.grid(True)
lines = []
lines.extend(axis1.plot(t, c, 'b'))
axis1.set_xlabel('Time')
axis1.set_ylabel('Current [A]')
axis1.set_xlim(xlim)
axis1.set_ylim([0, 6])
axis2 = axis1.twinx()
lines.extend(axis2.plot(t, v, 'r'))
axis2.set_ylabel('Voltage [V]')
axis2.set_ylim([11, 15])
figure.legend(lines, ('Current', 'Voltage'), 'upper left')
canvas = FigureCanvasAgg(figure)
canvas.print_figure(filename, dpi=80)
示例6: plot_raw_lightcurve
# 需要导入模块: from matplotlib.figure import Figure [as 别名]
# 或者: from matplotlib.figure.Figure import legend [as 别名]
def plot_raw_lightcurve(picid, lc0, psc_dir):
fig = Figure()
FigureCanvas(fig)
fig.set_size_inches(12, 7)
ax = fig.add_subplot(111)
ax.plot(lc0.loc[lc0.color == 'g'].target.values,
marker='o', label='Target') # .plot(marker='o')
ax.plot(lc0.loc[lc0.color == 'g'].reference.values,
marker='o', label='Reference') # .plot(marker='o')
fig.suptitle(f'Raw Flux - {picid}')
fig.tight_layout()
fig.legend()
plot_fn = os.path.join(psc_dir, 'plots', f'raw-flux-{picid}.png')
fig.savefig(plot_fn, transparent=False)
示例7: __init__
# 需要导入模块: from matplotlib.figure import Figure [as 别名]
# 或者: from matplotlib.figure.Figure import legend [as 别名]
class Gui:
def __init__( self ):
self.root = tk.Tk()
self.root.wm_title( "Log grapher" )
matplotlib.rc('font', size=8 )
self.fig = Figure( figsize=(11,5), dpi=100 )
self.fig.set_tight_layout( True )
self.axis = self.fig.add_subplot( 111 )
self.axis.set_title( 'Graph' )
self.axis.set_xlabel( 'X axis label' )
self.axis.set_ylabel( 'Y label' )
self.canvas = FigureCanvasTkAgg( self.fig, master=self.root )
self.canvas.show()
self.canvas.get_tk_widget().pack( side=TOP, fill=BOTH, expand=1 )
def setLabels( self, labelList ):
"""setLabels before doing anything else - configures axes etc"""
self.labels = labelList
for i in range( 0, len( labelList ) ):
self.axis.plot( [] )
self.fig.legend( self.axis.lines, self.labels, 'lower center', ncol=len(self.labels),
borderpad=0.3, handletextpad=0.2, columnspacing=0.3 )
def append( self, xVal, yValList ):
"""
yValList must be the same length as labelList, None values will be ignored.
Call update() afterwards.
"""
#print( "gui append " + str( xVal ) + ", " )
#pprint( yValList )
for idx, yVal in enumerate( yValList ):
if yVal is not None:
hl = self.axis.lines[idx]
hl.set_xdata( numpy.append( hl.get_xdata(), xVal ) )
hl.set_ydata( numpy.append( hl.get_ydata(), yVal ) )
def update( self ):
self.axis.relim()
self.axis.autoscale_view()
self.canvas.draw()
示例8: matplot_figure
# 需要导入模块: from matplotlib.figure import Figure [as 别名]
# 或者: from matplotlib.figure.Figure import legend [as 别名]
class matplot_figure(object):
"""\brief figure to show, which can be closed
"""
def __init__(self,):
"""\brief constuctor
"""
self.win = gtk.Window()
self.win.connect("delete-event", lambda widget, event: False)
self.win.set_default_size(640, 480)
self.win.set_title("Plot")
vbox = gtk.VBox()
self.win.add(vbox)
self.fig = Figure(figsize=(5, 4), dpi=100)
canvas = FigureCanvas(self.fig) # a gtk.DrawingArea
vbox.pack_start(canvas)
toolbar = NavigationToolbar(canvas, self.win)
vbox.pack_start(toolbar, False, False)
def show(self,):
"""\brief show window of the figure
"""
self.win.show_all()
def hide(self,):
"""\brief hide window of the figure
"""
self.win.hide()
def add_subplot(self, *args, **kargs):
"""\brief
\param *args
\param **kargs
"""
return self.fig.add_subplot(*args, **kargs)
def autofmt_xdate(self, *args, **kargs):
"""\brief autoformat date along X
\param *args
\param **kargs
"""
return self.fig.autofmt_xdate(*args, **kargs)
def legend(self, *args, **kargs):
"""\brief plot legend
\param *args
\param **kargs
"""
return self.fig.legend(*args, **kargs)
示例9: load_and_plot_diurnal
# 需要导入模块: from matplotlib.figure import Figure [as 别名]
# 或者: from matplotlib.figure.Figure import legend [as 别名]
def load_and_plot_diurnal(address, password, daysback):
address=address+'@gmail.com'
#print address, password
#Customizing Variables
### HOW FAR BACK? ###
daysback = int(daysback)
notsince = 0
since = (date.today() - timedelta(daysback)).strftime("%d-%b-%Y")
before = (date.today() - timedelta(notsince)).strftime("%d-%b-%Y")
SEARCH = '(SENTSINCE {si} SENTBEFORE {bf})'.format(si=since, bf=before)
BODY = '(BODY.PEEK[TEXT])'
ALL_HEADERS = '(BODY.PEEK[HEADER.FIELDS (DATE TO CC FROM SUBJECT)])'
DATE = '(BODY.PEEK[HEADER.FIELDS (DATE)])'
tyler = GmailAccount(username=address,password=password)
out = tyler.login()
#LOAD GMAIL EMAILS
received = tyler.load_parse_query(SEARCH, ALL_HEADERS, 'inbox')
#print 'loaded received...'
sent = tyler.load_parse_query(SEARCH, ALL_HEADERS, '[Gmail]/Sent Mail')
#print 'loaded received and sent mail!'
xr, yr = diurnalCompute(received)
xs, ys = diurnalCompute(sent)
fig=Figure(figsize=(14,8))
ax=fig.add_subplot(111)
p1, = ax.plot_date(xr, yr, '.', alpha=0.5, color='b', markersize=marker_size(len(xr)))
p2, = ax.plot_date(xs, ys, '.', alpha=0.7, color='r', markersize=marker_size(len(xr)))
fig.autofmt_xdate()
fig.legend((p1, p2,), ('Received','Sent'), 'upper center', numpoints=1, markerscale=4, fancybox=True)
ax.set_xlabel("Specific Date")
ax.set_ylabel("Time Of Day")
fig.tight_layout(pad=2)
#legend(('Received','Sent'), numpoints=1)
#ax.title("Received data for %s las %s days"%(address, str(daysback)))
#ax.xaxis.set_major_formatter(DateFormatter('%Y-%m-%d'))
'''
fig = figure()
plot_date(xr, yr, '.', alpha=0.7, color='b', markersize=marker_size(len(xr)))
#plot_date(xs, ys, '.', alpha=0.7, color='r', markersize=marker_size(len(xs)))
legend(('Received','Sent'), numpoints=1)
out = plt.setp(plt.xticks()[1], rotation=30)
'''
canvas=FigureCanvas(fig)
response=django.http.HttpResponse(content_type='image/png')
canvas.print_png(response)
return response
'''
示例10: plot_linear_relation
# 需要导入模块: from matplotlib.figure import Figure [as 别名]
# 或者: from matplotlib.figure.Figure import legend [as 别名]
def plot_linear_relation(x, y, x_err=None, y_err=None, title=None, point_label=None, legend=None, plot_range=None, plot_range_y=None, x_label=None, y_label=None, y_2_label=None, marker_style='-o', log_x=False, log_y=False, size=None, filename=None):
''' Takes point data (x,y) with errors(x,y) and fits a straight line. The deviation to this line is also plotted, showing the offset.
Parameters
----------
x, y, x_err, y_err: iterable
filename: string, PdfPages object or None
PdfPages file object: plot is appended to the pdf
string: new plot file with the given filename is created
None: the plot is printed to screen
'''
fig = Figure()
FigureCanvas(fig)
ax = fig.add_subplot(111)
if x_err is not None:
x_err = [x_err, x_err]
if y_err is not None:
y_err = [y_err, y_err]
ax.set_title(title)
if y_label is not None:
ax.set_ylabel(y_label)
if log_x:
ax.set_xscale('log')
if log_y:
ax.set_yscale('log')
if plot_range:
ax.set_xlim((min(plot_range), max(plot_range)))
if plot_range_y:
ax.set_ylim((min(plot_range_y), max(plot_range_y)))
if legend:
fig.legend(legend, 0)
ax.grid(True)
ax.errorbar(x, y, xerr=x_err, yerr=y_err, fmt='o', color='black') # plot points
# label points if needed
if point_label is not None:
for X, Y, Z in zip(x, y, point_label):
ax.annotate('{}'.format(Z), xy=(X, Y), xytext=(-5, 5), ha='right', textcoords='offset points')
line_fit, _ = np.polyfit(x, y, 1, full=False, cov=True)
fit_fn = np.poly1d(line_fit)
ax.plot(x, fit_fn(x), '-', lw=2, color='gray')
setp(ax.get_xticklabels(), visible=False) # remove ticks at common border of both plots
divider = make_axes_locatable(ax)
ax_bottom_plot = divider.append_axes("bottom", 2.0, pad=0.0, sharex=ax)
ax_bottom_plot.bar(x, y - fit_fn(x), align='center', width=np.amin(np.diff(x)) / 2, color='gray')
# plot(x, y - fit_fn(x))
ax_bottom_plot.grid(True)
if x_label is not None:
ax.set_xlabel(x_label)
if y_2_label is not None:
ax.set_ylabel(y_2_label)
ax.set_ylim((-np.amax(np.abs(y - fit_fn(x)))), (np.amax(np.abs(y - fit_fn(x)))))
ax.plot(ax.set_xlim(), [0, 0], '-', color='black')
setp(ax_bottom_plot.get_yticklabels()[-2:-1], visible=False)
if size is not None:
fig.set_size_inches(size)
if not filename:
fig.show()
elif isinstance(filename, PdfPages):
filename.savefig(fig)
elif filename:
fig.savefig(filename, bbox_inches='tight')
return fig
示例11: MplCanvas
# 需要导入模块: from matplotlib.figure import Figure [as 别名]
# 或者: from matplotlib.figure.Figure import legend [as 别名]
class MplCanvas(FigureCanvas):
def __init__(self, parent=None, width=8, height=10, dpi=80):
self.parent = parent
self.redraw_yticks = True
self.figure = Figure(figsize=(width, height), dpi=dpi, facecolor='#bbbbbb')
FigureCanvas.__init__(self, self.figure)
self.setParent(parent)
FigureCanvas.setSizePolicy(self,
QtGui.QSizePolicy.Expanding,
QtGui.QSizePolicy.Expanding)
FigureCanvas.updateGeometry(self)
def run(self, config_file, server):
self.mod = Dragonfly_Module(0, 0)
self.mod.ConnectToMMM(server)
self.msg_types = ['END_TASK_STATE', 'SESSION_CONFIG', 'EM_DECODER_CONFIGURATION']
self.msg_types.sort()
self.mod.Subscribe(MT_EXIT)
self.mod.Subscribe(rc.MT_PING)
for i in self.msg_types:
self.mod.Subscribe(eval('rc.MT_%s' % (i)))
self.mod.SendModuleReady()
print "Connected to Dragonfly at", server
print "mod_id = ", self.mod.GetModuleID()
self.config_file = config_file
self.load_config()
self.init_vars()
self.init_plot()
self.init_legend()
timer = QtCore.QTimer(self)
QtCore.QObject.connect(timer, QtCore.SIGNAL("timeout()"), self.timer_event)
timer.start(10)
def init_vars(self):
self.num_trials = 0
self.reset_counters()
self.msg_cnt = 0
self.console_disp_cnt = 0
def reset_counters(self):
self.trial_sync = 0
self.num_trials_postcalib = 0
self.num_trial_started_postcalib = 0
self.num_trial_givenup_postcalib = 0
self.num_trial_successful_postcalib = 0
self.shadow_num_trial_started_postcalib = 0
self.shadow_num_trial_givenup_postcalib = 0
self.shadow_num_trial_successful_postcalib = 0
self.started_window = []
self.givenup_window = []
self.success_window = []
self.shadow_started_window = []
self.shadow_givenup_window = []
self.shadow_success_window = []
self.percent_start = 0
self.percent_success = 0
self.percent_givenup = 0
self.hist_narrow_SUR = []
self.hist_narrow_GUR = []
self.hist_narrow_STR = []
self.hist_wide_SUR = []
self.hist_wide_GUR = []
self.hist_wide_STR = []
def update_gui_label_data(self):
self.parent.GALL.setText("%d" % self.num_trials_postcalib)
self.parent.GSTR.setText("%d" % self.num_trial_started_postcalib)
self.parent.GGUR.setText("%d" % self.num_trial_givenup_postcalib)
self.parent.GSUR.setText("%d" % self.num_trial_successful_postcalib)
#def reload_config(self):
# self.load_config()
# for ax in self.figure.axes:
# self.figure.delaxes(ax)
# self.figure.clear()
# self.draw()
# self.init_plot(True)
# self.init_legend()
# self.redraw_yticks = True
#def load_config(self):
# self.config = ConfigObj(self.config_file, unrepr=True)
def load_config(self):
self.config = SafeConfigParser()
self.config.read(self.config_file)
self.window_narrow = self.config.getint('general', 'window_narrow')
self.window_wide = self.config.getint('general', 'window_wide')
self.task_state_codes = {}
for k, v in self.config.items('task state codes'):
#.........这里部分代码省略.........
示例12: show_fit_at_position
# 需要导入模块: from matplotlib.figure import Figure [as 别名]
# 或者: from matplotlib.figure.Figure import legend [as 别名]
def show_fit_at_position(mcmc_set, fit_value, position, fit_name):
"""Create the result page showing the fit quality at the given position.
Parameters
----------
mcmc_set : MCMCSet object
The set of MCMC chains
fit_value : float
The quality of fit at the given position.
position : numpy.array
Array of (log10-transformed) parameter values at the given position.
fit_name : string
A shorthand name for the fit position, e.g., "max_likelihood". Should
conform to rules of Python variable naming (no spaces, doesn't
start with a number, etc.).
Returns
-------
A result object containing the fit value and the link to the accompanying
HTML plot page, if any.
"""
# If the MCMC object does not have a fit_plotting_function defined
# (for example, if it is a base MCMC object), then don't create a
# plot for visualization.
if not hasattr(mcmc_set.chains[0], 'fit_plotting_function'):
return Result(fit_value, None)
# Prepare html for page showing plots at position
html_str = "<html><head><title>Simulation of %s " \
"with %s parameter values</title></head>\n" \
% (mcmc_set.name, fit_name)
html_str += "<body><p>Simulation of %s with %s " \
"parameter values</p>\n" % (mcmc_set.name, fit_name)
# Show the plot vs. the data at the position
fig = mcmc_set.chains[0].fit_plotting_function(position=position)
img_filename = '%s_%s_plot.png' % (mcmc_set.name, fit_name)
fig.savefig(img_filename)
html_str += '<p><img src="%s" /></p>' % img_filename
# Show the plot of all observables at the position
chain0 = mcmc_set.chains[0]
tspan = chain0.options.tspan
observables = chain0.options.model.observables
x = chain0.simulate(position=position, observables=True)
fig = Figure()
ax = fig.gca()
lines = []
for o in observables:
line = ax.plot(tspan, x[o.name])
lines += line
ax.set_title("Observables at %s" % fit_name)
fig.legend(lines, [o.name for o in observables], 'lower right')
canvas = FigureCanvasAgg(fig)
fig.set_canvas(canvas)
img_filename = '%s_%s_species.png' % (mcmc_set.name, fit_name)
fig.savefig(img_filename)
html_str += '<p><img src="%s" /></p>' % img_filename
# Print the parameter values for the position as a dict that can be
# used to override the initial values
html_str += '<pre>%s_params = {\n' % fit_name
for i, p in enumerate(chain0.options.estimate_params):
html_str += "\t'%s': %.17g,\n" % \
(p.name, 10 ** position[i])
html_str += '}</pre>'
html_str += '</body></html>'
# Create the html file
html_filename = '%s_%s_plot.html' % (mcmc_set.name, fit_name)
with open(html_filename, 'w') as f:
f.write(html_str)
return Result(fit_value, html_filename)
示例13: XratersWindow
# 需要导入模块: from matplotlib.figure import Figure [as 别名]
# 或者: from matplotlib.figure.Figure import legend [as 别名]
#.........这里部分代码省略.........
self._startTime = time.time()
self._moveTime = self._startTime
self._Paused = False
def widget(self, name):
"""Helper function to retrieve widget handlers
"""
return self.builder.get_object(name)
def finish_initializing(self, builder):
"""finish_initalizing should be called after parsing the ui definition
and creating a XratersWindow object with it in order to finish
initializing the start of the new XratersWindow instance.
"""
#get a reference to the builder and set up the signals
self.builder = builder
self.builder.connect_signals(self)
#uncomment the following code to read in preferences at start up
dlg = PreferencesXratersDialog.NewPreferencesXratersDialog()
self.preferences = dlg.get_preferences()
#code for other initialization actions should be added here
self._accFigure = Figure(figsize=(8,6), dpi=72)
self._accAxis = self._accFigure.add_subplot(111)
self._accAxis.set_xlabel("time (s)")
self._accAxis.set_ylabel("acceleration (g)")
self._lines = self._accAxis.plot(self._time, self._accData[X],
self._time, self._accData[Y],
self._time, self._accData[Z],
animated=True)
self._accFigure.legend(self._lines, ("X", "Y", "Z"),
'upper center',
ncol=3)
self._accAxis.set_xlim(0, 2)
self._accAxis.set_ylim(-3, 3)
self._accCanvas = FigureCanvas(self._accFigure)
self._accCanvas.mpl_connect("draw_event", self._upd_background)
self.__background = self._accCanvas.copy_from_bbox(self._accAxis.bbox)
self._accCanvas.show()
self._accCanvas.set_size_request(600, 400)
vbMain = self.widget("vboxMain")
vbMain.pack_start(self._accCanvas, True, True)
vbMain.show()
vbMain.reorder_child(self._accCanvas, 2)
self._setBatteryIndicator(0)
def about(self, widget, data=None):
"""about - display the about box for xraters """
about = AboutXratersDialog.NewAboutXratersDialog()
response = about.run()
about.destroy()
def preferences(self, widget, data=None):
"""preferences - display the preferences window for xraters """
prefs = PreferencesXratersDialog.NewPreferencesXratersDialog()
response = prefs.run()
if response == gtk.RESPONSE_OK:
#make any updates based on changed preferences here
self.preferences = prefs.get_preferences()
prefs.destroy()
def quit(self, widget, data=None):
"""quit - signal handler for closing the XratersWindow"""
示例14: mplchart
# 需要导入模块: from matplotlib.figure import Figure [as 别名]
# 或者: from matplotlib.figure.Figure import legend [as 别名]
class mplchart(chart):
colours = dict(zip('red green blue yellow magenta black'.split(),
'r g b y m k'.split()))
def __init__(self, spurset, fef, parent):
chart.__init__(self, spurset, fef, parent)
# make the figure blend in with the native application look
bgcol = parent.palette().window().color().toRgb()
bgcol = [bgcol.redF(), bgcol.greenF(), bgcol.blueF()]
self.fig = Figure()
self.fig.set_facecolor(bgcol)
# a FigureCanvas can be added as a QWidget, so we use that
self.plot = FigureCanvas(self.fig)
self.plot.setParent(parent)
self.ax = self.fig.add_subplot(111)
# TODO skip this, just do a redraw() after initialization?
self.ax.set_xlim(self.spurset.RFmin, self.spurset.RFmax)
self.ax.set_ylim(-0.5*self.spurset.dspan, 0.5*self.spurset.dspan)
self.ax.grid(True)
self.fig.tight_layout()
# a second figure to hold the legend
self.legendFig = Figure()
self.legendFig.set_facecolor(bgcol)
self.legendCanvas = FigureCanvas(self.legendFig)
self.legendFig.legend(*self.ax.get_legend_handles_labels(),
loc='upper left')
# connect up the picker watching
self.picked_obj = None
self._pick = self.plot.mpl_connect('pick_event', self.onpick)
self._drag = self.plot.mpl_connect('motion_notify_event', self.ondrag)
self._drop = self.plot.mpl_connect('button_release_event', self.ondrop)
def legend(self):
return self.legendCanvas
def mkline(self, xdata, ydata, style, title):
return mpl.lines.Line2D(xdata, ydata, label=title,
color=self.colours[style[0]], ls=style[1])
def add_line(self, line):
self.ax.add_line(line)
def del_line(self, line):
self.ax.lines.remove(line)
def draw_spurs(self, obj):
chart.draw_spurs(self, obj)
def redraw(self):
self.ax.set_ylim(-0.5*self.spurset.dspan, 0.5*self.spurset.dspan)
self.ax.set_xlim(self.spurset.RFmin, self.spurset.RFmax)
# WHO WANTS TO BET THIS IS UNSUPPORTED?
# but damn, it works :/
self.legendFig.legends = []
self.legendFig.legend(*self.ax.get_legend_handles_labels(),
loc='upper left')
self.legendCanvas.draw()
self.plot.draw()
def draw_fef(self, obj):
chart.draw_fef(self, obj)
self.feflines[0].set_picker(10)
self.feflines[1].set_picker(10)
def onpick(self, event):
if event.mouseevent.button != 1:
# only picking on left-click atm
return
obj, x, y = event.artist, event.mouseevent.xdata, event.mouseevent.ydata
self.picked_obj = obj
self.pick(obj, x, y)
self.drag(obj, x, y)
def ondrag(self, event):
self.drag(self.picked_obj, event.xdata, event.ydata)
def ondrop(self, event):
if event.button != 1:
# only picking on left-click atm
return
self.drop(self.picked_obj, event.xdata, event.ydata)
self.picked_obj = None
示例15: Plot_Traces
# 需要导入模块: from matplotlib.figure import Figure [as 别名]
# 或者: from matplotlib.figure.Figure import legend [as 别名]
class Plot_Traces(Tk.Tk):
def __init__(self, root, folder):
Tk.Tk.__init__(self)
self.title("traces - " + folder)
self.root = root
self.folder = folder
self.protocol("WM_DELETE_WINDOW", self.closeGUI)
self.createTracesGUI()
def createTracesGUI(self):
# declare button variables
# control variables for neuron
self.neuronNumber = Tk.StringVar()
self.Vm_neuron = Tk.BooleanVar()
self.g_excit = Tk.BooleanVar()
self.g_inhib = Tk.BooleanVar()
self.G_ref = Tk.BooleanVar()
self.BPAP = Tk.BooleanVar()
self.spikesSelf = Tk.BooleanVar()
self.spikesTC = Tk.BooleanVar()
self.spikesRS = Tk.BooleanVar()
self.spikesFS = Tk.BooleanVar()
self.neuronAvail = True
# control variables for synapses
self.synapseNumber = Tk.StringVar()
self.Vm_syn = Tk.BooleanVar()
self.g = Tk.BooleanVar()
self.calcium = Tk.BooleanVar()
self.Mg = Tk.BooleanVar()
self.I_syn = Tk.BooleanVar()
self.I_NMDA = Tk.BooleanVar()
self.I_VGCC = Tk.BooleanVar()
self.P = Tk.BooleanVar()
self.B = Tk.BooleanVar()
self.D = Tk.BooleanVar()
self.V = Tk.BooleanVar()
# control variables for axes
self.y_min = Tk.StringVar()
self.y_max = Tk.StringVar()
self.x_min = Tk.StringVar()
self.x_max = Tk.StringVar()
self.step_y = 10
# self.step_x = 100
self.offValue = False # False = use provided values
self.legend = False # True = display label info
# create plotframe widget
mainFrame = Tk.Frame(self)
mainFrame.grid(column=0, row=0)
plotFrame = Tk.Frame(mainFrame, borderwidth=5, relief="sunken", width=500, height=500)
plotFrame.grid(column=0, row=0, columnspan=3, rowspan=2, sticky=(N, W, E), padx=(10, 10), pady=(10, 10))
selectionFrame = Tk.Frame(mainFrame, borderwidth=5, relief="sunken", width=500, height=125)
selectionFrame.grid(column=0, row=3, columnspan=7, rowspan=5, sticky=(N, S, E, W), padx=(10, 10), pady=(10, 10))
# create main figure
self.mainFig = Figure()
# create main plot canvas
self.canvas = FigureCanvasTkAgg(self.mainFig, master=plotFrame)
self.canvas.show()
self.canvas.get_tk_widget().pack(side=Tk.TOP, fill=Tk.BOTH, expand=1)
# create control for neuron variables
Tk.Label(selectionFrame, text="neuron: ").grid(column=0, row=0, sticky=(W))
self.neuronInput = Tk.Entry(selectionFrame, textvariable=self.neuronNumber, width=11)
self.neuronInput.grid(column=1, row=0, sticky=(W))
self.neuronNumber.set("0")
self.neuronInput.insert(0, "0")
self.neuronInput.bind("<Return>", self.renewCanvas)
self.neuronInput.bind("<Up>", lambda unit: self.nextUnit("neuron", +1))
self.neuronInput.bind("<Down>", lambda unit: self.nextUnit("neuron", -1))
check = Tk.Checkbutton(
selectionFrame,
text="neuron Vm",
command=lambda: self.checked(self.Vm_neuron),
variable=self.Vm_neuron,
onvalue=True,
offvalue=False,
)
check.grid(column=0, row=1, sticky=(W), padx=(0, 10))
self.Vm_neuron.set(False)
check = Tk.Checkbutton(
selectionFrame,
text="g excit",
command=lambda: self.checked(self.g_excit),
variable=self.g_excit,
onvalue=True,
offvalue=False,
)
check.grid(column=0, row=2, sticky=(W))
self.g_excit.set(False)
check = Tk.Checkbutton(
selectionFrame,
#.........这里部分代码省略.........