本文整理汇总了Python中matplotlib.figure.Figure.get_axes方法的典型用法代码示例。如果您正苦于以下问题:Python Figure.get_axes方法的具体用法?Python Figure.get_axes怎么用?Python Figure.get_axes使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类matplotlib.figure.Figure
的用法示例。
在下文中一共展示了Figure.get_axes方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: generateChart
# 需要导入模块: from matplotlib.figure import Figure [as 别名]
# 或者: from matplotlib.figure.Figure import get_axes [as 别名]
def generateChart(self):
u_genes = self.getUniqueGenes()
data = dict()
for gene, tags in u_genes.iteritems():
if not data.has_key(len(tags)):
data[len(tags)] = 0
data[len(tags)] += 1
data[0] = self._genes_c - len(u_genes.keys())
xs = list()
ys = list()
# Convert the values to %
for k, v in data.iteritems():
xs.append(k)
ys.append((float(v) / self._genes_c))
fig = Figure()
ax = fig.add_subplot(111)
ax.bar(xs, ys, width=0.5, align='center')
fig.get_axes()[0].set_ylabel('% of genes')
fig.get_axes()[0].set_xlabel('# of unique tags')
#fig.get_axes()[0].set_yscale('log')
canvas = FigureCanvasAgg(fig)
canvas.print_figure('enzyme-%s-length-%i.png' % \
(self.enzyme, self._original_tag_length),
dpi=96)
return data
示例2: case_alg_comparation
# 需要导入模块: from matplotlib.figure import Figure [as 别名]
# 或者: from matplotlib.figure.Figure import get_axes [as 别名]
def case_alg_comparation(cls, obs, algorithm):
wavPath = obs.export_to_wav()
# Canvas
micSn = kg.MicSignal.from_Obs(obs)
fig = Figure((15, 10))
fig.set_dpi(110)
results = algorithm.plot_alg(fig, micSn)
mpl = {str(algorithm): {'canvas': FigureCanvas(fig),
'axHandle': [Bar(ax) for ax in fig.get_axes()],
'setTime':True,
'animate':True
},
'aa': {'canvas': FigureCanvas(fig),
'axHandle': [Bar(ax) for ax in fig.get_axes()],
'setTime':True,
'animate':True
}
}
obj = cls(setup=True, wavPath=wavPath, t0=micSn.get_t0(), mpl=mpl)
#obj.timer.start()
return obj
示例3: mpl_widget
# 需要导入模块: from matplotlib.figure import Figure [as 别名]
# 或者: from matplotlib.figure.Figure import get_axes [as 别名]
class mpl_widget(QWidget):
def __init__(self, parent=None, mainWidget=None):
self._SELECTEDCELLS = list() # container for instances of selected cells, so we can delete them when we want
self._SELECTEDCELLS_IJ = list() # container for coords of selected cells, so we can delete them when we want
self._SELECTEDCELLLINES = list() # container for instances of selected cells, so we can delete them when we want
self._GRIDLINES = None
QWidget.__init__(self, parent)
self.mainWidget = mainWidget
self.create_main_frame()
self.mpl_menu = mpl_menu(self)
self.shift_is_held = False
#self.connect(self.mpl_menu, QtCore.SIGNAL('mySignal'), self.mySlot)
#print 'my parent is:', parent
self.clear_selection()
self.init_tooltips()
def init_tooltips(self):
self.canvas.setToolTip('If 2D plot => RMB click toggles menu <br> - RMB click selects cell <br> - selected cells are drawn with black border')
self.grid_cb.setToolTip('If 2D plot => show computational grid <br> If 1D plot => show normal gridlines')
self.cbar_button.setToolTip('If 2D plot => controls the color range. <br> Note: <br> - pressing UP and DOWN arrows cycles through colormaps <br> - dragging colorbar with RMB scales the color-range <br> - dragging colorbar with LMB shifts the color-range')
self.mpl_toolbar.setToolTip('Shows coordinates (i,j, lat,lon) and data-value(z) under the cursor. <br> if you see <i>>>></i> coordinates are not visible. Enlarge the window')
def create_main_frame(self):
self.fig = Figure(dpi=100)
self.canvas = FigureCanvas(self.fig)
self.canvas.setParent(self)
self.canvas.setFocusPolicy( Qt.ClickFocus )
self.canvas.setFocus()
self.mpl_toolbar = myNavigationToolbar(self.canvas, self)
self.canvas.mpl_connect('button_press_event', self.on_click)
self.canvas.mpl_connect('key_press_event', self.on_key_press)
self.canvas.mpl_connect('key_release_event', self.on_key_release)
#self.canvas.mpl_connect('button_press_event', self.disable_clicks)
self.cbar_button = QPushButton("Color Range")
self.cbar_button.setFocusPolicy( Qt.NoFocus )
self.grid_cb = QCheckBox("Show Grid")
self.grid_cb.setFocusPolicy( Qt.NoFocus )
self.grid_cb.stateChanged.connect(self.showGrid)
vbox = QVBoxLayout()
hbox = QHBoxLayout()
vbox.addWidget(self.canvas) # the matplotlib canvas
hbox.addWidget(self.mpl_toolbar)
hbox.addWidget(self.cbar_button)
hbox.addWidget(self.grid_cb)
vbox.addLayout(hbox)
self.setLayout(vbox)
def on_click(self, event):
if event.inaxes != self.get_axes()[0]: return
#if self.get_axes()[0].format_coord(event.x, event.y) == 'outside data area': return
if self.allow_menu():
self.allow_popup_menu = True
if self.shift_is_held:
self.allow_popup_menu = False
point = [int(event.xdata + .5), int(event.ydata + .5)]
#print '>>>', point, '\t currently {0} selected'.format(len(self._SELECTEDCELLS))
if event.button == 3 : #if RMB is clicked
# working with dialog for transect!
if self.mainWidget.transect_dlg:
if self.mainWidget.transect_dlg.toogle_show_after_selected_cell:
realx, realy = self.get_real_xy(event.xdata, event.ydata, self.mainWidget.detect_variable_dimensions())
realpoint = [realy, realx]
#print 'real xy:', realpoint
if self.mainWidget.transect_dlg.toogle_show_after_selected_cell == 1: # select point 1
self.allow_popup_menu = False
self.mainWidget.transect_dlg.data.set_p1(realpoint)
elif self.mainWidget.transect_dlg.toogle_show_after_selected_cell == 2: # select point 2
self.allow_popup_menu = False
self.mainWidget.transect_dlg.data.set_p2(realpoint)
self.mainWidget.transect_dlg.update()
self.mainWidget.transect_dlg.show()
# working with dialog for flux!
if self.mainWidget.flux_dlg:
if self.mainWidget.flux_dlg.toogle_show_after_selected_cell:
if self.mainWidget.flux_dlg.toogle_show_after_selected_cell == 1: # select point 1
self.allow_popup_menu = False
self.mainWidget.flux_dlg.data.set_p1(point)
elif self.mainWidget.flux_dlg.toogle_show_after_selected_cell == 2: # select point 2
self.allow_popup_menu = False
self.mainWidget.flux_dlg.data.set_p2(point)
self.mainWidget.flux_dlg.update()
self.mainWidget.flux_dlg.show()
if len(self._SELECTEDCELLS) == 0: # if no cell is selected
self.add_selected_cell(point)
#.........这里部分代码省略.........
示例4: VNA
# 需要导入模块: from matplotlib.figure import Figure [as 别名]
# 或者: from matplotlib.figure.Figure import get_axes [as 别名]
#.........这里部分代码省略.........
size = self.sweep_size
return self.dut[0:size]/self.short[0:size]
def impedance(self):
size = self.sweep_size
return 50.0 * (self.open[0:size] - self.load[0:size]) * (self.dut[0:size] - self.short[0:size]) / ((self.load[0:size] - self.short[0:size]) * (self.open[0:size] - self.dut[0:size]))
def gamma(self):
z = self.impedance()
return (z - 50.0)/(z + 50.0)
def plot_gain(self):
if self.cursor is not None: self.cursor.hide().disable()
matplotlib.rcdefaults()
self.figure.clf()
self.figure.subplots_adjust(left = 0.12, bottom = 0.12, right = 0.88, top = 0.98)
axes1 = self.figure.add_subplot(111)
axes1.cla()
axes1.xaxis.set_major_formatter(FuncFormatter(metric_prefix))
axes1.yaxis.set_major_formatter(FuncFormatter(metric_prefix))
axes1.tick_params('y', color = 'blue', labelcolor = 'blue')
axes1.yaxis.label.set_color('blue')
gain = self.gain()
axes1.plot(self.xaxis, 20.0 * np.log10(np.absolute(gain)), color = 'blue', label = 'Gain')
axes2 = axes1.twinx()
axes2.spines['left'].set_color('blue')
axes2.spines['right'].set_color('red')
axes1.set_xlabel('Hz')
axes1.set_ylabel('Gain, dB')
axes2.set_ylabel('Phase angle')
axes2.tick_params('y', color = 'red', labelcolor = 'red')
axes2.yaxis.label.set_color('red')
axes2.plot(self.xaxis, np.angle(gain, deg = True), color = 'red', label = 'Phase angle')
self.cursor = datacursor(axes = self.figure.get_axes(), formatter = LabelFormatter(), display = 'multiple')
self.canvas.draw()
def plot_magphase(self, data):
if self.cursor is not None: self.cursor.hide().disable()
matplotlib.rcdefaults()
self.figure.clf()
self.figure.subplots_adjust(left = 0.12, bottom = 0.12, right = 0.88, top = 0.98)
axes1 = self.figure.add_subplot(111)
axes1.cla()
axes1.xaxis.set_major_formatter(FuncFormatter(metric_prefix))
axes1.yaxis.set_major_formatter(FuncFormatter(metric_prefix))
axes1.tick_params('y', color = 'blue', labelcolor = 'blue')
axes1.yaxis.label.set_color('blue')
axes1.plot(self.xaxis, np.absolute(data), color = 'blue', label = 'Magnitude')
axes2 = axes1.twinx()
axes2.spines['left'].set_color('blue')
axes2.spines['right'].set_color('red')
axes1.set_xlabel('Hz')
axes1.set_ylabel('Magnitude')
axes2.set_ylabel('Phase angle')
axes2.tick_params('y', color = 'red', labelcolor = 'red')
axes2.yaxis.label.set_color('red')
axes2.plot(self.xaxis, np.angle(data, deg = True), color = 'red', label = 'Phase angle')
self.cursor = datacursor(axes = self.figure.get_axes(), formatter = LabelFormatter(), display = 'multiple')
self.canvas.draw()
def plot_open(self):
self.plot_magphase(self.open[0:self.sweep_size])
def plot_short(self):
self.plot_magphase(self.short[0:self.sweep_size])
示例5: streamPick
# 需要导入模块: from matplotlib.figure import Figure [as 别名]
# 或者: from matplotlib.figure.Figure import get_axes [as 别名]
#.........这里部分代码省略.........
and _pick.waveform_id.station_code == station\
and _pick.waveform_id.channel_code == channel:
self._picks.remove(_pick)
def _getPicks(self):
'''
Create a list of picks for the current plot
'''
this_st_picks = []
for _i, pick in enumerate(self._picks):
if pick.waveform_id.station_code == self._current_stname and\
self._current_st[0].stats.starttime <\
pick.time < self._current_st[0].stats.endtime:
this_st_picks.append(_i)
return [self._picks[i] for i in this_st_picks]
def _getPickXPosition(self, picks):
'''
Convert picktimes into relative positions along x-axis
'''
xpicks = []
for _pick in picks:
xpicks.append((_pick.time-self._current_st[0].stats.starttime)
/ self._current_st[0].stats.delta)
return np.array(xpicks)
def _drawPicks(self, draw=True):
'''
Draw picklines onto axes
'''
picks = self._getPicks()
xpicks = self._getPickXPosition(picks)
for _ax in self.fig.get_axes():
lines = []
labels = []
transOffset = offset_copy(_ax.transData, fig=self.fig,
x=5, y=0, units='points')
for _i, _xpick in enumerate(xpicks):
if picks[_i].phase_hint == 'S':
color = 'r'
elif picks[_i].phase_hint == 'P':
color = 'g'
else:
color = 'b'
if _ax.channel != picks[_i].waveform_id.channel_code:
alpha = .1
else:
alpha = .8
lines.append(matplotlib.lines.Line2D([_xpick, _xpick],
[_ax.get_ylim()[0]*.9, _ax.get_ylim()[1]*.8],
color=color, alpha=alpha))
lines[-1].obspy_pick = picks[_i]
labels.append(matplotlib.text.Text(_xpick,
_ax.get_ylim()[0]*.8, text=picks[_i].phase_hint,
color=color, size=10, alpha=alpha,
transform=transOffset))
# delete all artists
del _ax.artists[0:]
# add updated objects
for line in lines:
_ax.add_artist(line)
for label in labels:
示例6: FigurePanel
# 需要导入模块: from matplotlib.figure import Figure [as 别名]
# 或者: from matplotlib.figure.Figure import get_axes [as 别名]
#.........这里部分代码省略.........
names_ordered.append('Name')
_dframes = []
for df in self.current_dataframes:
_dframes.append(df[names_ordered])
self._kdraw(_dframes, self.current_datacolors)
def _kdraw(self, dframes, colors):
self.fig.clear()
self.start_busy()
task = DrawThread(self, dframes, colors)
task.start()
def on_play(self, event):
self.mode_run = True
self.run_explorer = True
self.new_order = []
# ---- dibujar clusters/datos seleccionados
self.control_panel.run_fig()
def on_sort_and_filter(self, event):
self.run_explorer = True
cdf = self.current_dataframes
if cdf is None or cdf == []:
return
self.old_order = cdf[0].columns.tolist()[:-1]
ItemsPickerFilterDialog(self, self.old_order)
def on_highligh(self, event):
_label_aux = ''
if self.run_explorer:
for axe in self.fig.get_axes():
lines = []
for line in axe.get_children():
if isinstance(line, Line2D):
if self.ldic.get(line.get_color()) is not None:
_label_aux = self.ldic.get(line.get_color())
line.set_label('shape = ' + self.ldic.get(line.get_color()))
lines.append(line)
else:
line.set_label('')
h = resaltar(lines, highlight_color=self.ax_conf.highlight_color,
formatter='{label}'.format)
if lines != []:
h.show_highlight(lines[0])
self.run_explorer = False
self.canvas_draw()
def on_config(self, event):
if self.figure_config_dialog_ref is None:
self.figure_config_dialog_ref = FigureConfigDialog(self)
else:
self.figure_config_dialog_ref.nb.SetSelection(0)
self.figure_config_dialog_ref.ShowModal()
def g_figure(self):
return self.ch_graph.GetSelection()
def get_choice_grafic(self):
grid = wx.FlexGridSizer(cols=2)
sampleList = self.get_item_list()
self.ch_graph = wx.Choice(self, -1, choices=sampleList)
self.ch_graph.SetSelection(0)
示例7: EegpyBaseWin
# 需要导入模块: from matplotlib.figure import Figure [as 别名]
# 或者: from matplotlib.figure.Figure import get_axes [as 别名]
class EegpyBaseWin(gtk.Window):
programName = "eegpy: Window-widget"
panePosDef = 0
x=None
y=None
# Konstruktor
def __init__(self):
gobject.threads_init()
gtk.Window.__init__(self,gtk.WINDOW_TOPLEVEL)
self.setupGUI()
def cb_quit(self, b):
self.window.hide()
gtk.main_quit()
# This callback quits the program
def delete_event(self, widget, event, data=None):
self.hide()
gtk.main_quit()
return False
def setupGUI(self):
self.set_default_size(700,500)
self.set_title(self.programName)
# Set a handler for delete_event that immediately
# exits GTK.
self.connect("delete_event", self.delete_event)
# Sets the border width of the window.
self.set_border_width(0)
self.hpane = gtk.HPaned()
self.add(self.hpane)
#self.setupMenu()
self.inner_pane = gtk.VPaned()
self.hpane.add1(self.inner_pane)
self.upper_hbox = gtk.HBox()
self.lower_vbox = gtk.VBox()
self.inner_pane.add1(self.upper_hbox)
self.inner_pane.add2(self.lower_vbox)
self.setupCanvas()
#self.setupLog()
self.set_icon_list(eegpy_logo("small"), eegpy_logo("large"))
self.show_all()
self.panePosDef = self.hpane.get_position()
def setupLog(self):
self.frameLog = gtk.Frame("Log")
self.logbuffer = gtk.TextBuffer(None)
self.lvSw = gtk.ScrolledWindow()
self.logview = gtk.TextView(self.logbuffer)
self.logview.set_editable(False)
#self.logview.set_buffer(self.logbuffer)
self.logview.set_border_width(1)
self.lvSw.set_policy(gtk.POLICY_AUTOMATIC, gtk.POLICY_AUTOMATIC);
self.lvSw.add(self.logview)
self.frameLog.add(self.lvSw)
self.upper_hbox.pack_end(self.frameLog)
pass
def log(self,message):
"""logs a message to the log window"""
message=message+"\n"
self.logbuffer.insert(self.logbuffer.get_start_iter(),message)#_at_cursor(message, len(message))
#self.lvSw.set_vadjustment(self.lvSw.get_vadjustment().lower)
def setupCanvas(self):
self.f = Figure(figsize=(5,4), dpi=100, subplotpars=SubplotParams(left=0.06, top=0.95, right=0.97, bottom=0.1))
self.setupSubplots()
self.canvas = FigureCanvas(self.f)
#self.canvas.show()
self.lower_vbox.pack_start(self.canvas)
#self.canvas.get_tk_widget().pack(side=TOP, fill=BOTH, expand=1)
self.toolbar = NavigationToolbar( self.canvas, self.window )
self.lower_vbox.pack_start(self.toolbar, False, False)
def setupSubplots(self):
self.f.clear()
self.a = self.f.add_subplot(111)
self.subplAxes = self.f.get_axes()
示例8: LPlotWidget
# 需要导入模块: from matplotlib.figure import Figure [as 别名]
# 或者: from matplotlib.figure.Figure import get_axes [as 别名]
class LPlotWidget(LWidget):
def __init__(self, parent=None):
super(LPlotWidget, self).__init__(parent)
self.setName(WIDGET_NAME)
self.buildUi()
self.dataContainer = LMyDataContainer(self)
self.actions = LMyActions(self.dataContainer,self)
self.updateUi()
@LInAndOut(DEBUG & WIDGETS)
def buildUi(self):
self.verticalLayout = QVBoxLayout(self)
#width, height = (14, 4)
#width, height = figaspect(2.)
width = 1
height = 1
dpi = 72
self.figure = Figure(figsize=(width, height), dpi=dpi) # <-- figs created with same geometry!
self.figure2 = Figure(figsize=(width, height), dpi=dpi)
#self.figure = Figure(dpi=dpi) # <-- figs created with same geometry!
#self.figure2 = Figure(dpi=dpi)
#self.axe111 = self.figure2.add_axes((0,0,1,1),title="My Axe Title",xlabel='X',ylabel='Y')
#self.axesSubplot_111 = self.figure.add_subplot(2,2,1)
#print self.axesSubplot_111.get_position()
#self.axesSubplot_111 = self.figure.add_subplot(2,2,2)
#print self.axesSubplot_111.get_position()
#self.axesSubplot_111 = self.figure.add_subplot(2,2,3)
#self.axesSubplot_111.set_frame_on(False)
#self.bbox = self.axesSubplot_111.get_position()
#print self.bbox.__class__.__name__
#print self.axesSubplot_111.get_position()
self.axesSubplot_111 = self.figure.add_subplot(2,2,4)
self.axesSubplot_111.plot([1,0])
#print self.axesSubplot_111.get_position()
#self.axesSubplot_111.set_position(self.bbox)
#self.axesSubplot_111.set_position([0.54772727, 0.53636364, 0.9, 0.9 ])
self.axesSubplot_111 = self.figure2.add_subplot(2,2,2) # <-- creation in fig2
self.axesSubplot_111 = self.figure2.add_subplot(1,1,1) # <-- position in fig2 doesn't impact position in fig1
print self.axesSubplot_111.__class__.__name__
print self.axesSubplot_111.get_position()
print self.axesSubplot_111.get_axes_locator()
#self.bbox = self.axesSubplot_111.get_position()
self.axesSubplot_111.grid(color='g', linestyle='-.', linewidth=1)
self.axesSubplot_111.plot([0,1])
#Change to the figure
#self.axesSubplot_111.set_figure(self.figure)
#self.figure.add_axes(self.axesSubplot_111)
x0 = 1.0
y0 = 1.0
xspan = 8.0
yspan = 8.0
pos = [x0,y0,xspan,yspan]
self.addAxesSubplot(self.axesSubplot_111, position=pos)
#self.axesSubplot_111.reset_position()
#self.axesSubplot_111.set_position(pos=pos,which='both')
#self.axesSubplot_111.set_position(self.bbox,which='both') # <-- as if the bbox where scalled differently
self.figureCanvas = FigureCanvas(self.figure) # <-- figure required
self.verticalLayout.addWidget(self.figureCanvas)
#FigureCanvas.setSizePolicy(self.figureCanvas, QSizePolicy.Expanding, QSizePolicy.Expanding)
#FigureCanvas.updateGeometry(self.figureCanvas)
@LInAndOut(DEBUG & WIDGETS)
def updateUi(self):
self.figure.suptitle(self.dataContainer.figureTitle)
#----------------------------------------------------------------------
# Interface (set)
@LInAndOut(DEBUG & WIDGETS)
def setOptions(self, options):
super(LPlotWidget, self).setOptions(options)
if options.verboseLevel is not None:
self.setVerboseLevel(options.verboseLevel)
if options.figureTitle is not None:
self.setFigureTitle(options.figureTitle)
self.updateUi()
@LInAndOut(DEBUG & WIDGETS)
def setVerboseLevel(self, level):
self.dataContainer.verboseLevel = level
#----------------------------------------------------------------------
# Interface (get)
#----------------------------------------------------------------------
# QT SLOTS
@LInAndOut(DEBUG & WIDGETS)
def setFigureTitle(self, title):
self.dataContainer.figureTitle = title
#.........这里部分代码省略.........
示例9: PlotPanel
# 需要导入模块: from matplotlib.figure import Figure [as 别名]
# 或者: from matplotlib.figure.Figure import get_axes [as 别名]
class PlotPanel(BasePanel):
"""
MatPlotlib 2D plot as a wx.Panel, suitable for embedding
in any wx.Frame. This does provide a right-click popup
menu for configuration, zooming, saving an image of the
figure, and Ctrl-C for copy-image-to-clipboard.
For more features, see PlotFrame, which embeds a PlotPanel
and also provides, a Menu, StatusBar, and Printing support.
"""
def __init__(self, parent, size=(700, 450), dpi=150, axisbg=None,
facecolor=None, fontsize=9, trace_color_callback=None,
output_title='plot', with_data_process=True, **kws):
self.trace_color_callback = trace_color_callback
matplotlib.rc('axes', axisbelow=True)
matplotlib.rc('lines', linewidth=2)
matplotlib.rc('xtick', labelsize=fontsize, color='k')
matplotlib.rc('ytick', labelsize=fontsize, color='k')
matplotlib.rc('legend', fontsize=fontsize)
matplotlib.rc('grid', linewidth=0.5, linestyle='-')
BasePanel.__init__(self, parent,
output_title=output_title, **kws)
self.conf = PlotConfig(panel=self, with_data_process=with_data_process)
self.data_range = {}
self.win_config = None
self.cursor_callback = None
self.lasso_callback = None
self.cursor_mode = 'zoom'
self.parent = parent
self.figsize = (size[0]*1.0/dpi, size[1]*1.0/dpi)
self.dpi = dpi
if facecolor is not None:
self.conf.bgcolor = facecolor
if axisbg is not None:
self.conf.bgcolor = axisbg
# axesmargins : margins in px left/top/right/bottom
self.axesmargins = (30, 30, 30, 30)
self.BuildPanel()
self.conf.user_limits = {} # [None, None, None, None]
self.data_range = {}
self.conf.zoom_lims = []
self.conf.axes_traces = {}
def plot(self, xdata, ydata, side='left', title=None,
xlabel=None, ylabel=None, y2label=None,
use_dates=False, **kws):
"""
plot (that is, create a new plot: clear, then oplot)
"""
allaxes = self.fig.get_axes()
if len(allaxes) > 1:
for ax in allaxes[1:]:
if ax in self.data_range:
self.data_range.pop(ax)
self.fig.delaxes(ax)
self.data_range = {}
self.conf.zoom_lims = []
self.conf.axes_traces = {}
self.clear()
axes = self.axes
if side == 'right':
axes = self.get_right_axes()
self.conf.ntrace = 0
self.conf.yscale = 'linear'
self.conf.user_limits[axes] = [None, None, None, None]
if xlabel is not None:
self.set_xlabel(xlabel, delay_draw=True)
if ylabel is not None:
self.set_ylabel(ylabel, delay_draw=True)
if y2label is not None:
self.set_y2label(y2label, delay_draw=True)
if title is not None:
self.set_title(title, delay_draw=True)
if use_dates is not None:
self.use_dates = use_dates
return self.oplot(xdata, ydata, side=side, **kws)
def oplot(self, xdata, ydata, side='left', label=None,
xlabel=None, ylabel=None, y2label=None, title=None,
dy=None, ylog_scale=None, xlog_scale=None, grid=None,
xmin=None, xmax=None, ymin=None, ymax=None,
color=None, style=None, drawstyle=None,
linewidth=2, marker=None, markersize=None,
refresh=True, show_legend=None,
legend_loc='best', legend_on=True, delay_draw=False,
bgcolor=None, framecolor=None, gridcolor=None,
labelfontsize=None, legendfontsize=None,
fullbox=None, axes_style=None, zorder=None, viewpad=None, **kws):
""" basic plot method, overplotting any existing plot """
self.cursor_mode = 'zoom'
conf = self.conf
conf.plot_type = 'lineplot'
#.........这里部分代码省略.........
示例10: __init__
# 需要导入模块: from matplotlib.figure import Figure [as 别名]
# 或者: from matplotlib.figure.Figure import get_axes [as 别名]
#.........这里部分代码省略.........
:param xmax: Requested maximum value for the X axis.
:type xmax: float
:param ymax: Requested maximum value for the Y axis.
:type ymax: float
:return: None
"""
# FlatCAMApp.App.log.debug("PC.adjust_axes()")
width = xmax - xmin
height = ymax - ymin
try:
r = width / height
except ZeroDivisionError:
FlatCAMApp.App.log.error("Height is %f" % height)
return
canvas_w, canvas_h = self.canvas.get_width_height()
canvas_r = float(canvas_w) / canvas_h
x_ratio = float(self.x_margin) / canvas_w
y_ratio = float(self.y_margin) / canvas_h
if r > canvas_r:
ycenter = (ymin + ymax) / 2.0
newheight = height * r / canvas_r
ymin = ycenter - newheight / 2.0
ymax = ycenter + newheight / 2.0
else:
xcenter = (xmax + xmin) / 2.0
newwidth = width * canvas_r / r
xmin = xcenter - newwidth / 2.0
xmax = xcenter + newwidth / 2.0
# Adjust axes
for ax in self.figure.get_axes():
if ax._label != 'base':
ax.set_frame_on(False) # No frame
ax.set_xticks([]) # No tick
ax.set_yticks([]) # No ticks
ax.patch.set_visible(False) # No background
ax.set_aspect(1)
ax.set_xlim((xmin, xmax))
ax.set_ylim((ymin, ymax))
ax.set_position([x_ratio, y_ratio, 1 - 2 * x_ratio, 1 - 2 * y_ratio])
# Sync re-draw to proper paint on form resize
self.canvas.draw()
def auto_adjust_axes(self, *args):
"""
Calls ``adjust_axes()`` using the extents of the base axes.
:rtype : None
:return: None
"""
xmin, xmax = self.axes.get_xlim()
ymin, ymax = self.axes.get_ylim()
self.adjust_axes(xmin, ymin, xmax, ymax)
def zoom(self, factor, center=None):
"""
Zooms the plot by factor around a given
center point. Takes care of re-drawing.
:param factor: Number by which to scale the plot.
:type factor: float
示例11: __init__
# 需要导入模块: from matplotlib.figure import Figure [as 别名]
# 或者: from matplotlib.figure.Figure import get_axes [as 别名]
class asaplotbase:
"""
ASAP plotting base class based on matplotlib.
"""
def __init__(self, rows=1, cols=0, title='', size=None, buffering=False):
"""
Create a new instance of the ASAPlot plotting class.
If rows < 1 then a separate call to set_panels() is required to define
the panel layout; refer to the doctext for set_panels().
"""
self.is_dead = False
self.figure = Figure(figsize=size, facecolor='#ddddee')
self.canvas = None
self.set_title(title)
self.subplots = []
if rows > 0:
self.set_panels(rows, cols)
# Set matplotlib default colour sequence.
self.colormap = "green red black cyan magenta orange blue purple yellow pink".split()
c = asaprcParams['plotter.colours']
if isinstance(c,str) and len(c) > 0:
self.colormap = c.split()
# line styles need to be set as a list of numbers to use set_dashes
self.lsalias = {"line": [1,0],
"dashdot": [4,2,1,2],
"dashed" : [4,2,4,2],
"dotted" : [1,2],
"dashdotdot": [4,2,1,2,1,2],
"dashdashdot": [4,2,4,2,1,2]
}
styles = "line dashed dotted dashdot".split()
c = asaprcParams['plotter.linestyles']
if isinstance(c,str) and len(c) > 0:
styles = c.split()
s = []
for ls in styles:
if self.lsalias.has_key(ls):
s.append(self.lsalias.get(ls))
else:
s.append('-')
self.linestyles = s
self.color = 0;
self.linestyle = 0;
self.attributes = {}
self.loc = 0
self.buffering = buffering
self.events = {'button_press':None,
'button_release':None,
'motion_notify':None}
def _alive(self):
# Return True if the GUI alives.
if (not self.is_dead) and \
self.figmgr and hasattr(self.figmgr, "num"):
figid = self.figmgr.num
# Make sure figid=0 is what asapplotter expects.
# It might be already destroied/overridden by matplotlib
# commands or other methods using asaplot.
return _pylab_helpers.Gcf.has_fignum(figid) and \
(self.figmgr == _pylab_helpers.Gcf.get_fig_manager(figid))
return False
def _subplotsOk(self, rows, cols, npanel=0):
"""
Check if the axes in subplots are actually the ones plotted on
the figure. Returns a bool.
This method is to detect manual layout changes using mpl methods.
"""
# compare with user defined layout
if (rows is not None) and (rows != self.rows):
return False
if (cols is not None) and (cols != self.cols):
return False
# check number of subplots
figaxes = self.figure.get_axes()
np = self.rows*self.cols
if npanel > np:
return False
if len(figaxes) != np:
return False
if len(self.subplots) != len(figaxes):
return False
# compare axes instance in this class and on the plotter
ok = True
for ip in range(np):
if self.subplots[ip]['axes'] != figaxes[ip]:
ok = False
break
return ok
### Delete artists ###
#.........这里部分代码省略.........
示例12: Figure
# 需要导入模块: from matplotlib.figure import Figure [as 别名]
# 或者: from matplotlib.figure.Figure import get_axes [as 别名]
from matplotlib.backends.backend_gtkcairo import FigureCanvasGTKCairo as FigureCanvas
win = gtk.Window()
win.connect("destroy", lambda x: gtk.main_quit())
win.set_default_size(800, 600)
win.set_title("Embedding in GTK")
box = gtk.VBox();
win.add(box)
f = Figure(figsize=(5, 4), dpi=100)
a = f.add_subplot(111)
print f.get_axes()[0]
t = arange(0.0, 3.0, 0.01)
s = sin(2*pi*t)
a.plot(t, s)
s = cos(2*pi*t)
a.plot(t, s)
s = sin(2*pi*t)*cos(2*pi*t)
a.plot(t, s)
canvas = FigureCanvas(f) # a gtk.DrawingArea
box.pack_start(canvas,expand=True,padding=10)
示例13: ImagePanel
# 需要导入模块: from matplotlib.figure import Figure [as 别名]
# 或者: from matplotlib.figure.Figure import get_axes [as 别名]
class ImagePanel(wx.Panel):
"""This class displays 2D data as a color plot"""
def __init__(self,parent,posFunction=None,setMin=None,setMax=None):
"""This creates an ImagePanel
Keyword arguments:
parent -- The container which will hold the panel
posFunction -- function to be updated with mouse position
setMin -- function to be called on left click
setMax -- function to be called on right click
"""
wx.Panel.__init__(self,parent)
self.Bind(wx.EVT_PAINT,self.__OnPaint)
self.posFunction = posFunction#Function to call on mouse movement
self.setMin = setMin#Function to call on right click
self.setMax = setMax#Function to call on left click
#The figure which holds the graph
self.figure = Figure(figsize=(1,1),dpi=512)
#The object where the graph is drawn
self.canvas = FigureCanvas(self,-1,self.figure)
self.canvas.Bind(wx.EVT_MOTION,self.__OnMouseMove)
self.canvas.Bind(wx.EVT_LEFT_UP,self.__OnMouseLeft)
self.canvas.Bind(wx.EVT_RIGHT_UP,self.__OnMouseRight)
self.cmap = cm.spectral#The color map for the graph
#Known file formats for saving images
self.handlers={u"BMP":wx.BITMAP_TYPE_BMP,
u"JPG":wx.BITMAP_TYPE_JPEG,
u"PNG":wx.BITMAP_TYPE_PNG,
u"PCX":wx.BITMAP_TYPE_PCX,
u"PNM":wx.BITMAP_TYPE_PNM,
u"TIF":wx.BITMAP_TYPE_TIF}
def __OnPaint(self,event):
"""Event handler to redraw graph when panel is redrawn."""
self.canvas.draw()
event.Skip()
def __OnMouseMove(self,event):
"""Event handler when the mouse moves over the graph"""
(x,y) = event.GetPosition()
if self.posFunction is None: return
self.posFunction(x/32,y/4)
def __OnMouseLeft(self,event):
"""Event handler for left clicking on the graph."""
(x,y) = event.GetPosition()
if self.setMin is None:
None
else:
self.setMin(x/32,y/4)
event.Skip()
def __OnMouseRight(self,event):
"""Event handler for right clicking on the graph."""
(x,y) = event.GetPosition()
if self.setMax is None:
None
else:
self.setMax(x/32,y/4)
event.Skip()
def update(self,data,vmin=10,vmax=20):
"""Change the dataset for the graph
Keyword arguments:
data -- 2D numpy array
vmin -- floor value for graphing
vmax -- ceiling value for graphing
"""
self.data=data
self.figure.clear()
self.figure.add_axes((0,0,1,1),autoscale_on=True,frameon=False,yticks=[0,1],xticks=[0,1])
self.figure.get_axes()[-1].get_xaxis().set_visible(False)
self.figure.get_axes()[-1].get_yaxis().set_visible(False)
self.figure.get_axes()[-1].imshow(data,cmap=self.cmap,vmin=vmin,vmax=vmax,aspect="auto",interpolation='none')
self.figure.canvas.draw()
self.Refresh()
def saveImage(self,path):
"""Saves the graph to an image file"""
bitmap = wx.EmptyBitmap(512,512,24)
memdc = wx.MemoryDC(bitmap)
self.figure.canvas.draw(memdc)
image = wx.Bitmap.ConvertToImage(bitmap)
image.SaveFile(path,self.handlers[path[-3:].encode('ascii')])
def copyToClipboard(self):
"""Copies the image of the graph to the system Clipboard."""
if wx.TheClipboard.Open():
bitmap = wx.EmptyBitmap(512,512,24)
memdc = wx.MemoryDC(bitmap)
self.figure.canvas.draw(memdc)
wx.TheClipboard.Clear()
wx.TheClipboard.SetData(wx.BitmapDataObject(bitmap))
#.........这里部分代码省略.........
示例14: PlotPanel
# 需要导入模块: from matplotlib.figure import Figure [as 别名]
# 或者: from matplotlib.figure.Figure import get_axes [as 别名]
class PlotPanel (wx.Panel):
"""The PlotPanel has a Figure and a Canvas"""
def __init__(self, parent, color=(255, 255, 255), dpi=None, **kwargs):
# initialize Panel
if 'id' not in kwargs.keys():
kwargs['id'] = wx.ID_ANY
if 'style' not in kwargs.keys():
kwargs['style'] = wx.NO_FULL_REPAINT_ON_RESIZE
wx.Panel.__init__(self, parent, **kwargs)
# subplotparams = SubplotParams(0.02, 0.02, 0.98, 0.98, 0.1, 0.1)
# initialize matplotlib stuff
self.figure = Figure((2.1, 2.97), dpi)
self.canvas = FigureCanvasWxAgg(self, -1, self.figure)
self.SetColor(color)
sizer = wx.BoxSizer(wx.VERTICAL)
sizer.Add(self.canvas, 1, wx.EXPAND | wx.SHAPED, 0)
self.SetSizer(sizer)
self.Bind(wx.EVT_SIZE, self.set_size)
self.draw()
self.Refresh()
def SetColor(self, rgbtuple=None):
"""Set figure and canvas colours to be the same."""
if rgbtuple is None:
rgbtuple = wx.SystemSettings.GetColour(wx.SYS_COLOUR_BTNFACE).Get()
clr = [c/255. for c in rgbtuple]
self.figure.set_facecolor(clr)
self.figure.set_edgecolor(clr)
self.canvas.SetBackgroundColour(wx.Colour(*rgbtuple))
def set_size(self, evt=None):
if self.ClientSize[0] > 0 and self.ClientSize[1] > 0:
self.canvas.SetSize(self.ClientSize)
self.canvas.draw()
def draw(self):
raise NoImplementedError # abstract, to be overridden by child classes
def image_grid(self, num_rows, num_cols):
return ImageGrid(self.figure, 111,
share_all = True,
nrows_ncols = (num_rows, num_cols),
cbar_size = "3%",
cbar_pad = 0.02,
cbar_mode = 'single')
def get_norm(self, vmin, vmax):
return matplotlib.colors.normalize(vmax=vmax, vmin=vmin)
def save_to_pdf(self, pdfpages):
old_fig = self.figure
self.figure = Figure((8.5, 11), dpi=300)
canvas = matplotlib.backends.backend_pdf.FigureCanvasPdf(self.figure)
self.draw()
pdfpages.savefig(self.figure)
self.figure = old_fig
def align_subplots(self):
xmin = matplotlib.numpy.inf
xmax = - matplotlib.numpy.inf
for subplot in self.figure.get_axes():
xmin = min(xmin, subplot.get_xlim()[0])
xmax = max(xmax, subplot.get_xlim()[1])
for subplot in self.figure.get_axes():
subplot.set_xlim(xmin, xmax)
示例15: PlotPanel
# 需要导入模块: from matplotlib.figure import Figure [as 别名]
# 或者: from matplotlib.figure.Figure import get_axes [as 别名]
class PlotPanel(BasePanel):
"""
MatPlotlib 2D plot as a wx.Panel, suitable for embedding
in any wx.Frame. This does provide a right-click popup
menu for configuration, zooming, saving an image of the
figure, and Ctrl-C for copy-image-to-clipboard.
For more features, see PlotFrame, which embeds a PlotPanel
and also provides, a Menu, StatusBar, and Printing support.
"""
def __init__(self, parent, size=None, dpi=150,
axissize=None, axisbg=None, fontsize=9,
trace_color_callback=None,
output_title='plot', **kws):
if size is None: size=(700, 450)
self.trace_color_callback = trace_color_callback
matplotlib.rc('axes', axisbelow=True)
matplotlib.rc('lines', linewidth=2)
matplotlib.rc('xtick', labelsize=fontsize, color='k')
matplotlib.rc('ytick', labelsize=fontsize, color='k')
matplotlib.rc('legend', fontsize=fontsize)
matplotlib.rc('grid', linewidth=0.5, linestyle='-')
BasePanel.__init__(self, parent,
output_title=output_title, **kws)
self.conf = PlotConfig()
self.data_range = {}
self.win_config = None
self.cursor_callback = None
self.lasso_callback = None
self.parent = parent
self.figsize = (size[0]*1.0/dpi, size[1]*1.0/dpi)
self.dpi = dpi
if axissize is None: axissize = [0.16, 0.16, 0.72, 0.75]
if axisbg is None: axisbg='#FEFFFE'
self.axisbg = axisbg
self.axissize = axissize
self.BuildPanel()
self.user_limits = {} # [None, None, None, None]
self.data_range = {}
self.zoom_lims = []
self.axes_traces = {}
def plot(self, xdata, ydata, side='left', title=None,
xlabel=None, ylabel=None, y2label=None,
use_dates=False, **kws):
"""
plot (that is, create a new plot: clear, then oplot)
"""
allaxes = self.fig.get_axes()
if len(allaxes) > 1:
for ax in allaxes[1:]:
if ax in self.data_range:
self.data_range.pop(ax)
self.fig.delaxes(ax)
self.data_range = {}
self.zoom_lims = []
self.axes_traces = {}
self.clear()
axes = self.axes
if side == 'right':
axes = self.get_right_axes()
self.conf.ntrace = 0
self.cursor_mode = 'zoom'
self.conf.plot_type = 'lineplot'
self.user_limits[axes] = [None, None, None, None]
if xlabel is not None:
self.set_xlabel(xlabel)
if ylabel is not None:
self.set_ylabel(ylabel)
if y2label is not None:
self.set_y2label(y2label)
if title is not None:
self.set_title(title)
if use_dates is not None:
self.use_dates = use_dates
return self.oplot(xdata, ydata, side=side, **kws)
def oplot(self, xdata, ydata, side='left', label=None,
xlabel=None, ylabel=None, y2label=None, title=None,
dy=None, ylog_scale=False, grid=None,
xmin=None, xmax=None, ymin=None, ymax=None,
color=None, style=None, drawstyle=None,
linewidth=2, marker=None, markersize=None,
autoscale=True, refresh=True, show_legend=None,
legend_loc='ur', legend_on=True, delay_draw=False,
bgcolor=None, framecolor=None, gridcolor=None,
labelfontsize=None, legendfontsize=None,
fullbox=True, zorder=None, **kws):
""" basic plot method, overplotting any existing plot """
axes = self.axes
if side == 'right':
#.........这里部分代码省略.........