本文整理汇总了Python中matplotlib.figure.Figure.get_figwidth方法的典型用法代码示例。如果您正苦于以下问题:Python Figure.get_figwidth方法的具体用法?Python Figure.get_figwidth怎么用?Python Figure.get_figwidth使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类matplotlib.figure.Figure
的用法示例。
在下文中一共展示了Figure.get_figwidth方法的12个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: MatplotlibWidget
# 需要导入模块: from matplotlib.figure import Figure [as 别名]
# 或者: from matplotlib.figure.Figure import get_figwidth [as 别名]
class MatplotlibWidget(FigureCanvas):
"""Ultimately, this is a QWidget (as well as a FigureCanvasAgg, etc.)."""
def __init__(self, parent=None, name=None, width=5, height=4, dpi=100, bgcolor=None):
self.parent = parent
if self.parent:
bgc = parent.backgroundBrush().color()
bgcolor = float(bgc.red())/255.0, float(bgc.green())/255.0, float(bgc.blue())/255.0
#bgcolor = "#%02X%02X%02X" % (bgc.red(), bgc.green(), bgc.blue())
self.fig = Figure(figsize=(width, height), dpi=dpi, facecolor=bgcolor, edgecolor=bgcolor)
self.axes = self.fig.add_subplot(111)
# We want the axes cleared every time plot() is called
self.axes.hold(False)
self.compute_initial_figure()
FigureCanvas.__init__(self, self.fig)
self.reparent(parent, QPoint(0, 0))
FigureCanvas.setSizePolicy(self,
QSizePolicy.Expanding,
QSizePolicy.Expanding)
FigureCanvas.updateGeometry(self)
def sizeHint(self):
w = self.fig.get_figwidth()
h = self.fig.get_figheight()
return QSize(w, h)
def minimumSizeHint(self):
return QSize(10, 10)
def compute_initial_figure(self):
pass
示例2: MatplotlibWidget
# 需要导入模块: from matplotlib.figure import Figure [as 别名]
# 或者: from matplotlib.figure.Figure import get_figwidth [as 别名]
class MatplotlibWidget(FigureCanvas):
"""Ultimately, this is a QWidget (as well as a FigureCanvasAgg, etc.)."""
def __init__(self, parent=None, name=None, width=5, height=4, dpi=100,
bgcolor=None):
QtGui.QWidget.__init__(self, parent)
self.parent = parent
self.fig = Figure(figsize=(width, height), dpi=dpi,
facecolor=bgcolor, edgecolor=bgcolor)
FigureCanvas.__init__(self, self.fig)
self.setParent(parent)
self.setSizePolicy(QtGui.QSizePolicy.Expanding,
QtGui.QSizePolicy.Expanding)
self.updateGeometry()
def sizeHint(self):
w = self.fig.get_figwidth()*self.fig.get_dpi()
h = self.fig.get_figheight()*self.fig.get_dpi()
return QtCore.QSize(w, h)
@QtCore.pyqtSlot()
def clear(self):
''' Clears the figure. '''
self.fig.clear()
@QtCore.pyqtSlot()
def reset(self):
'''
Clears the figure and prepares a new plot.
The difference between this and clear() is that
the latter only clears the figure, while this
also prepares the canvas for the plot commands.
'''
self.clear()
self.axes = self.fig.add_subplot(111)
self.axes.hold(False) # We want the axes cleared every time plot() is called
@QtCore.pyqtSlot (wave.Wave)
def plot1d (self, data, redraw=True):
'''
Called to plot the specified wave. It will be passed
to matplotlib's plot() as it is. This typically means
that if it's a higher-D matrix, it will be plotted as a
series of 1D graphs.
'''
w = wave.WCast(data)
self.axes.plot(w.dim[0].range, w)
if redraw == True:
self.draw()
@QtCore.pyqtSlot (wave.Wave)
def plot2d (self, data, redraw=True):
'''
Called to plot the specified 2D wave. Uses matplotlib's
imshow() to show the specified image.
'''
self.axes.imshow(data, aspect='auto', extent=wave.WCast(data).imlim)
if redraw == True:
self.draw()
@QtCore.pyqtSlot(wave.Wave)
def plot(self, data, redraw=True):
'''
Convenience wrapper for plot1d() or plot2d().
Assuming that 'data' is one single Wave (or ndarray object),
it calls plot1d() or plot2d(), depending on the dimensionality
of the data.
'''
if hasattr(data, '__iter__') and not hasattr(data, 'ndim'):
data_list = data
data = data_list[0]
if not hasattr(data, 'ndim'):
log.error ("Don't know how to plot data type: %s" % data)
return
if data.ndim == 1:
self.plot1d(data, redraw)
elif data.ndim == 2:
self.plot2d(data, redraw)
else:
self.axes.clear()
w = data.view(wave.Wave)
axinfo_str = ''.join([ ("axis %d: %f...%f (units: '%s')\n"
% (j, i.offset, i.end, i.units))
for i,j in zip(w.dim, range(w.ndim))])
self.axes.text (0.05, 0.95, "Don't know how to display wave!\n\nname: "
"%s\ndimensions: %d\n%s\n%s" %
(w.infs('name'), w.ndim, axinfo_str, pprint.pformat(w.info)),
transform=self.axes.transAxes, va='top')
self.draw()
示例3: Chart
# 需要导入模块: from matplotlib.figure import Figure [as 别名]
# 或者: from matplotlib.figure.Figure import get_figwidth [as 别名]
#.........这里部分代码省略.........
oscData=self.data.adLine()
else:
return
if oscData!=None:
x=range(len(self.data.close))
ax.plot(x,oscData,'g-',label=type)
ax.set_xlim(x[0],x[-1])
#legenda
leg = ax.legend(loc='best', fancybox=True)
leg.get_frame().set_alpha(0.5)
self.formatDateAxis(self.oscPlot)
self.fixOscLabels()
self.fixTimeLabels()
def fixOscLabels(self):
"""Metoda ustawia zakres osi poprawny dla danego oscylatora. Ponadto przenosi
etykiety na prawą stronę, żeby nie nachodziły na kurs akcji"""
ax=self.oscPlot
type=self.oscType
if type == 'ROC':
ax.set_ylim(-100, 100)
elif type == 'RSI':
ax.set_ylim(0, 100)
ax.set_yticks([30,70])
elif type == 'williams':
ax.set_ylim(-100,0)
for tick in ax.yaxis.get_major_ticks():
tick.label1On = False
tick.label2On = True
tick.label2.set_size(7)
def formatDateAxis(self,ax):
"""Formatuje etykiety osi czasu."""
chartWidth=int(self.fig.get_figwidth()*self.fig.get_dpi()*self.maxSize)
t = TextPath((0,0), '9999-99-99', size=7)
labelWidth = int(t.get_extents().width)
num_ticks=chartWidth/labelWidth/2
length=len(self.data.date)
if(length>num_ticks):
step=length/num_ticks
else:
step=1
x=range(0,length,step)
ax.xaxis.set_major_locator(FixedLocator(x))
ticks=ax.get_xticks()
labels=[]
for i, label in enumerate(ax.get_xticklabels()):
label.set_size(7)
index=int(ticks[i])
if(index>=len(self.data.date)):
labels.append('')
else:
labels.append(self.data.date[index].strftime("%Y-%m-%d"))
label.set_horizontalalignment('center')
ax.xaxis.set_major_formatter(FixedFormatter(labels))
def fixTimeLabels(self):
"""Włącza wyświetlanie etykiet osi czasu pod odpowiednim (tzn. najniższym)
wykresem, a usuwa w pozostałych"""
#oscylator jest zawsze na samym dole
if self.oscPlot!=None and self.oscPlot.get_visible():
for label in self.mainPlot.get_xticklabels():
label.set_visible(False)
for label in self.volumeBars.get_xticklabels():
label.set_visible(False)
for label in self.oscPlot.get_xticklabels():
示例4: MatplotlibWidget
# 需要导入模块: from matplotlib.figure import Figure [as 别名]
# 或者: from matplotlib.figure.Figure import get_figwidth [as 别名]
#.........这里部分代码省略.........
QSizePolicy.Expanding)
FigureCanvas.updateGeometry(self)
# Color bar related stuffs:
self.showColorBar = False
self.colorBars = None
# color associated to position where mask=0 :
self.bgColor = 'w'#QColor('white') if bgColor==None else bgColor
# Default colormap (~rainbow) : black-blue-green-yellow-red
self.colorMapString = '0;0;0.5;0.0;0.75;1.0;1.;1.0#' \
'0;0;0.5;1;0.75;1;1;0.#' \
'0;0;0.25;1;0.5;0;1;0.'
self.setColorMapFromString(self.colorMapString)
self.update()
# Signal stuffs:
#self.mpl_connect('button_release_event', self.onRelease)
self.mpl_connect('motion_notify_event', self.onMove)
self.mpl_connect('button_press_event', self.onClick)
def setBackgroundColor(self, color):
if type(color) == QColor:
self.bgColor = tuple([c/255. for c in color.getRgb()])
else:
self.bgColor = color # assume letter code/ hex color string / ...
# anything supported by matplotlib.colors
#TODO maybe do some checks ?
if debug:print 'setting over/under color ', self.bgColor
self.colorMap.set_under(color=self.bgColor)
self.colorMap.set_over(color=self.bgColor)
def sizeHint(self):
w = self.fig.get_figwidth()
h = self.fig.get_figheight()
return QSize(w, h)
def getColorMapString(self):
return self.colorMapString
def setColorMapFromString(self, scm):
if debug : print 'MatplotlibWidget.setColorMapFromString'
scm = str(scm)
if debug : print ' recieved scm:', scm
# Make sure we do not have any negative values :
subResult = re.subn('(\+[0-9]+(\.\d*)?)','0.',scm)
if debug and subResult[1] > 0:
print ' !!! found negative values !!!'
sys.exit(1)
scm = subResult[0]
self.colorMapString = scm
if debug : print ' negative filtered scm :', scm
self.colorMap = cmstring_to_mpl_cmap(scm)
# Set colors corresponding to [minval-1 , minval] to background color:
self.setBackgroundColor(self.bgColor)
def setGraphMode(self, m):
if self.graphMode == m:
return
if debug: print 'xndarrayViewRenderer.setGraphMode:',m
self.graphMode = m
self.computeFigure()
def minimumSizeHint(self):
示例5: BrowserMatPlotFrame
# 需要导入模块: from matplotlib.figure import Figure [as 别名]
# 或者: from matplotlib.figure.Figure import get_figwidth [as 别名]
class BrowserMatPlotFrame(QtGui.QWidget):
"定义画图的页面"
def __init__(self, parent = None):
QtGui.QWidget.__init__(self)
self.parent = parent
self.status_bar = parent.status_bar
#State
self.draw_node_labels_tf = True
self.draw_axis_units_tf = False
self.draw_grid_tf = False
self.g = None
#PATH used in drawing STEP hierarchy, co-occurence, context
self.step_path = parent.step_path
#MPL figure
self.dpi = 100
self.fig = Figure((5.0, 4.0), dpi=self.dpi)
self.fig.subplots_adjust(left=0,right=1,top=1,bottom=0)
#QT canvas
self.canvas = FigureCanvas(self.fig)
self.canvas.setParent(self)
self.canvas.mpl_connect('pick_event', self.on_pick) #used when selectingpyth canvas objects
self.canvas.setSizePolicy(QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Expanding)
self.axes = self.fig.add_subplot(111)
#self.axes.hold(False) #clear the axes every time plot() is called
self.mpl_toolbar = NavigationToolbar(self.canvas, self)
#GUI controls
self.mode_combo = QComboBox()
self.mode_combo.addItems(["Graph Test",
"Graph Test Numpy",
"STEP Hierarchy",
"STEP Co-occurence",
"STEP Context"])
self.mode_combo.setMinimumWidth(200)
self.draw_button = QPushButton("&Draw/Refresh")
self.connect(self.draw_button, QtCore.SIGNAL('clicked()'), self.on_draw)
self.node_size = QSpinBox(self)
self.node_size.setSingleStep(5)
self.node_size.setMaximum(100)
self.node_size.setValue(25)
self.node_size_label = QLabel('Node Size (%):')
# connection set in on_draw() method
#Horizontal layout
hbox = QtGui.QHBoxLayout()
#Adding matplotlib widgets
for w in [self.mode_combo, 's', self.node_size_label, self.node_size, self.draw_button]:
if w == 's': hbox.addStretch()
else:
hbox.addWidget(w)
hbox.setAlignment(w, Qt.AlignVCenter)
#Vertical layout. Adding all other widgets, and hbox layout.
vbox = QtGui.QVBoxLayout()
vbox.addWidget(self.mpl_toolbar)
vbox.addWidget(self.canvas)
vbox.addLayout(hbox)
self.setLayout(vbox)
self.canvas.setFocus(True)
def draw_axis_units(self):
fw = self.fig.get_figwidth()
fh = self.fig.get_figheight()
l_margin = .4 / fw #.4in
b_margin = .3 / fh #.3in
if self.draw_axis_units_tf == True:
self.fig.subplots_adjust(left=l_margin,right=1,top=1,bottom=b_margin)
else:
self.fig.subplots_adjust(left=0,right=1,top=1,bottom=0)
self.canvas.draw()
def draw_grid(self):
if self.draw_grid_tf == False:
self.draw_grid_tf = True
else:
self.draw_grid_tf = False
self.axes.grid(self.draw_grid_tf)
self.canvas.draw()
def on_draw(self):
draw_mode = self.mode_combo.currentText()
self.axes.clear()
if self.g != None:
if hasattr(self.g, 'destruct'):
self.g.destruct()
#.........这里部分代码省略.........
示例6: PlotterWidget
# 需要导入模块: from matplotlib.figure import Figure [as 别名]
# 或者: from matplotlib.figure.Figure import get_figwidth [as 别名]
#.........这里部分代码省略.........
if ids is None:
self.selected = []
if (old_selection == self.selected and old_selection != [])\
or self.selected != []:
if self.selected != [] and old_selection != self.selected: # Color new selection
for indx in self.selected:
self.highlighted = self.axes.plot(self.xs[indx],
self.ys[indx], 'or')[0]
if old_selection == self.selected: # Turn off existing selection
self.selected = []
if old_selection != []: # Do not color old selection
for indx in old_selection:
self.axes.plot(self.xs[indx], self.ys[indx],
'ob', picker = 3)
self.canvas.draw()
return True
return False
# ---------------------- NAVIGATION CONTROLS ---------------------------
# Mouse movement (with or w/o button press) handling
def onMouseMotion(self, event):
"""Handles the panning."""
if event.button == 1:
xmotion = self.lastX - event.x
ymotion = self.lastY - event.y
self.lastX = event.x
self.lastY = event.y
figsize = min(self.fig.get_figwidth(), self.fig.get_figheight())
xmin, xmax = self.calcTranslate(self.axes.get_xlim(),
xmotion, figsize)
ymin, ymax = self.calcTranslate(self.axes.get_ylim(),
ymotion, figsize)
self.axes.set_xlim(xmin, xmax)
self.axes.set_ylim(ymin, ymax)
self.canvas.draw()
# Note: the dtuple is in data coordinates, the motion is in pixels,
# we estimate how much motion there is based on the figsize and then
# scale it appropriately to the data coordinates to get the proper
# offset in figure limits.
def calcTranslate(self, dtuple, motion, figsize):
"""Calculates the translation necessary in one direction given a
mouse drag in that direction.
dtuple
The current limits in a single dimension
motion
The number of pixels the mouse was dragged in the dimension.
This may be negative.
figsize
The approximate size of the figure.
"""
dmin, dmax = dtuple
drange = dmax - dmin
dots = self.fig.dpi * figsize
offset = float(motion * drange) / float(dots)
newmin = dmin + offset
newmax = dmax + offset
示例7: __init__
# 需要导入模块: from matplotlib.figure import Figure [as 别名]
# 或者: from matplotlib.figure.Figure import get_figwidth [as 别名]
#.........这里部分代码省略.........
if line is not None:
lines.append(line[0])
lbl = line[0].get_label()
if lbl == '':
lbl = str(i)
labels.append(lbl)
if len(lines):
fp = FP(size=rcParams['legend.fontsize'])
#fsz = fp.get_size_in_points() - len(lines)
fsz = fp.get_size_in_points() - max(len(lines),self.cols)
#fp.set_size(max(fsz,6))
fp.set_size(max(fsz,8))
sp['axes'].legend(tuple(lines), tuple(labels),
self.loc, prop=fp)
#else:
# sp['axes'].legend((' '))
from matplotlib.artist import setp
fpx = FP(size=rcParams['xtick.labelsize'])
xts = fpx.get_size_in_points()- (self.cols)/2
fpy = FP(size=rcParams['ytick.labelsize'])
yts = fpy.get_size_in_points() - (self.rows)/2
fpa = FP(size=rcParams['axes.labelsize'])
fpat = FP(size=rcParams['axes.titlesize'])
axsize = fpa.get_size_in_points()
tsize = fpat.get_size_in_points()-(self.cols)/2
for sp in self.subplots:
ax = sp['axes']
ax.title.set_size(tsize)
setp(ax.get_xticklabels(), fontsize=xts)
setp(ax.get_yticklabels(), fontsize=yts)
off = 0
if self.cols > 1: off = self.cols
ax.xaxis.label.set_size(axsize-off)
off = 0
if self.rows > 1: off = self.rows
ax.yaxis.label.set_size(axsize-off)
def save(self, fname=None, orientation=None, dpi=None, papertype=None):
"""
Save the plot to a file.
fname is the name of the output file. The image format is determined
from the file suffix; 'png', 'ps', and 'eps' are recognized. If no
file name is specified 'yyyymmdd_hhmmss.png' is created in the current
directory.
"""
from asap import rcParams
if papertype is None:
papertype = rcParams['plotter.papertype']
if fname is None:
from datetime import datetime
dstr = datetime.now().strftime('%Y%m%d_%H%M%S')
fname = 'asap'+dstr+'.png'
d = ['png','.ps','eps', 'svg']
from os.path import expandvars
fname = expandvars(fname)
if fname[-3:].lower() in d:
try:
if fname[-3:].lower() == ".ps":
from matplotlib import __version__ as mv
w = self.figure.get_figwidth()
h = self.figure.get_figheight()
if orientation is None:
# oriented
if w > h:
orientation = 'landscape'
else:
orientation = 'portrait'
from matplotlib.backends.backend_ps import papersize
pw,ph = papersize[papertype.lower()]
ds = None
if orientation == 'landscape':
ds = min(ph/w, pw/h)
else:
ds = min(pw/w, ph/h)
ow = ds * w
oh = ds * h
self.figure.set_size_inches((ow, oh))
self.figure.savefig(fname, orientation=orientation,
papertype=papertype.lower())
self.figure.set_size_inches((w, h))
print 'Written file %s' % (fname)
else:
if dpi is None:
dpi =150
self.figure.savefig(fname,dpi=dpi)
print 'Written file %s' % (fname)
except IOError, msg:
#print 'Failed to save %s: Error msg was\n\n%s' % (fname, err)
asaplog.post()
asaplog.push('Failed to save %s: Error msg was\n\n%s' % (fname, str(msg)))
asaplog.post( 'ERROR' )
return
else:
示例8: PlotPanel
# 需要导入模块: from matplotlib.figure import Figure [as 别名]
# 或者: from matplotlib.figure.Figure import get_figwidth [as 别名]
class PlotPanel(wx.Panel):
def __init__(self, parent, toolbar_visible=False, **kwargs):
"""
A panel which contains a matplotlib figure with (optionally) a
toolbar to zoom/pan/ect.
Inputs:
parent : the parent frame/panel
toolbar_visible : the initial state of the toolbar
**kwargs : arguments passed on to
matplotlib.figure.Figure
Introduces:
figure : a matplotlib figure
canvas : a FigureCanvasWxAgg from matplotlib's
backends
toggle_toolbar() : to toggle the visible state of the toolbar
show_toolbar() : to show the toolbar
hide_toolbar() : to hide the toolbar
Subscribes to:
'TOGGLE_TOOLBAR' : if data=None or data=self will toggle the
visible state of the toolbar
'SHOW_TOOLBAR' : if data=None or data=self will show the
toolbar
'HIDE_TOOLBAR' : if data=None or data=self will hide the
toolbar
"""
wx.Panel.__init__(self, parent)
self.figure = Figure(**kwargs)
self.canvas = Canvas(self, wx.ID_ANY, self.figure)
self.toolbar = CustomToolbar(self.canvas, self)
self.toolbar.Show(False)
self.toolbar.Realize()
toolbar_sizer = wx.BoxSizer(orient=wx.HORIZONTAL)
self.x_coord = wx.StaticText(self, label='x:')
self.y_coord = wx.StaticText(self, label='y:')
toolbar_sizer.Add(self.toolbar, proportion=2)
toolbar_sizer.Add(self.x_coord, proportion=1,
flag=wx.ALIGN_CENTER_VERTICAL|wx.ALIGN_LEFT|wx.LEFT, border=5)
toolbar_sizer.Add(self.y_coord, proportion=1,
flag=wx.ALIGN_CENTER_VERTICAL|wx.ALIGN_LEFT|wx.LEFT, border=5)
sizer = wx.BoxSizer(orient=wx.VERTICAL)
sizer.Add(toolbar_sizer, proportion=0, flag=wx.EXPAND)
sizer.Add(self.canvas, proportion=1, flag=wx.EXPAND)
self.SetSizer(sizer)
figheight = self.figure.get_figheight()
figwidth = self.figure.get_figwidth()
min_size = self.set_minsize(figwidth ,figheight)
self._toolbar_visible = toolbar_visible
if toolbar_visible:
self.show_toolbar()
else:
self.hide_toolbar()
self.canvas.Bind(wx.EVT_LEFT_DCLICK, self.toggle_toolbar)
self._last_time_coordinates_updated = 0.0
self._coordinates_blank = True
self.canvas.mpl_connect('motion_notify_event', self._update_coordinates)
# ---- Setup Subscriptions
pub.subscribe(self._toggle_toolbar, topic="TOGGLE_TOOLBAR")
pub.subscribe(self._show_toolbar, topic="SHOW_TOOLBAR")
pub.subscribe(self._hide_toolbar, topic="HIDE_TOOLBAR")
self.axes = {}
def _save_history(self):
if (hasattr(self.toolbar, '_views') and
hasattr(self.toolbar, '_positions')):
self._old_history = {}
self._old_history['views'] = copy.copy(self.toolbar._views)
self._old_history['positions'] = copy.copy(self.toolbar._positions)
def _restore_history(self):
if hasattr(self, '_old_history'):
self.toolbar._views = self._old_history['views']
self.toolbar._positions = self._old_history['positions']
self.toolbar.set_history_buttons()
if hasattr(self.toolbar, '_update_view'):
self.toolbar._update_view()
def clear(self, keep_history=False):
self._save_history()
self.axes = {}
self.figure.clear()
gc.collect()
def set_minsize(self, figwidth, figheight):
dpi = self.figure.get_dpi()
# compensate for toolbar height, even if not visible, to keep
# it from riding up on the plot when it is visible and the
# panel is shrunk down.
toolbar_height = self.toolbar.GetSize()[1]
min_size_x = dpi*figwidth
min_size_y = dpi*figheight+toolbar_height
#.........这里部分代码省略.........
示例9: __init__
# 需要导入模块: from matplotlib.figure import Figure [as 别名]
# 或者: from matplotlib.figure.Figure import get_figwidth [as 别名]
class PlotWindow:
def __init__(self, plot, title="", lines=[], shown=False):
self.plot=plot
self.window=None
self.vbox=None
self.figure=None
self.canvas=None
self.axes=None
self.legend=None
self.show_cursors=False
self.plot.shown=shown
if shown:
self.show()
def show(self):
self.vbox = gtk.VBox()
self.figure = Figure(figsize=(5,4))
self.figure.set_size_inches(self.plot.figwidth, self.plot.figheight)
self.window = gtk.Window()
self.window.connect("destroy", self.destroy_cb)
# self.window.connect("set-focus", self.set_focus_cb)
self.window.connect("notify::is-active", self.window_focus_cb)
self.window.add(self.vbox)
self.canvas = FigureCanvas(self.figure) # a gtk.DrawingArea
self.draw()
self.update(limits=True)
self.vbox.pack_start(self.canvas)
toolbar = NavigationToolbar(self.canvas, self.window)
self.vbox.pack_start(toolbar, False, False)
if self.plot.window_size != (0,0):
self.window.resize(self.plot.window_size[0],
self.plot.window_size[1])
else:
self.window.resize(400, 300)
if self.plot.window_pos != (0,0):
self.window.move(self.plot.window_pos[0],
self.plot.window_pos[1])
self.window.set_title(self.plot.title)
self.cursors, = self.axes.plot(self.plot.lines[0].get_data()[0], self.plot.lines[0].get_data()[1])
self.cursors.set_linestyle("None")
self.cursors.set_markersize(10)
self.cursors.set_markeredgewidth(2)
self.cursors.set_markeredgecolor("k")
self.cursors.set_antialiased(False)
self.window.show_all()
# self.plot.figwidth=self.figure.get_figwidth()
# self.plot.figheight=self.figure.get_figheight()
# self.pos=self.window.get_position()
self.plot.shown=True
def set_focus_cb(self,window,data):
print "Hej!"
def window_focus_cb(self,window,data):
print self.plot.window_size, self.plot.window_pos
print "window_focus_cb:", self.plot.title
if window.get_property('is-active'):
#self.plot.parent.notebook.set_current_page(1)
print "is-active"
if self.plot.parent.plt_combo.get_selected_data() != self.plot:
print "selecting item..."
self.plot.parent.plt_combo.select_item_by_data(self.plot)
self.plot.window_size=self.window.get_size()
self.plot.window_pos=self.window.get_position()
self.plot.figwidth=self.figure.get_figwidth()
self.plot.figheight=self.figure.get_figheight()
def draw(self, items=None, sources=None):
legend=[]
print "drawing "+self.plot.title
def myfmt(x,y): return 'x=%1.6g\ny=%1.6g'%(x,y)
self.figure.clf()
self.axes = self.figure.add_subplot(111)
#self.axes = self.figure.add_axes([0.10,0.10,0.85,0.85])
#self.figure.subplots_adjust(bottom=0.15, left=0.15)
self.axes.set_autoscale_on(False)
self.axes.format_coord = myfmt
# self.btn_axes=self.figure.add_axes([0,0,0.1,0.05], frameon=True)
# self.cursor_a_btn=Button(self.btn_axes,"A")
#.........这里部分代码省略.........
示例10: PlotPanel
# 需要导入模块: from matplotlib.figure import Figure [as 别名]
# 或者: from matplotlib.figure.Figure import get_figwidth [as 别名]
#.........这里部分代码省略.........
#update the plots
self.UpdatePlot()
def OnSelectAx2(self,xmin,xmax):
self.figure_canvas.draw()
if self.data == None:
return
self.SetLimits(tRange=[xmin,xmax])
#update the mask and plot
self.UpdatePlot()
def OnSelectAx3(self,xmin,xmax):
#mask the data array
if self.data == None:
return
self.SetLimits(tRange=[xmin,xmax])
#update the mask and plot
self.UpdatePlot()
def OnSize(self,e):
if self.GetAutoLayout():
self.Layout()
left = 60
right = 30
top = 30
bottom = 40
wspace = 100
dpi = self.figure.dpi
h = self.figure.get_figheight()*dpi
w = self.figure.get_figwidth()*dpi
#figure out the margins
self.figure.subplots_adjust(left=left/w,
right=1-right/w,
bottom=bottom/h,
top=1-top/h,
wspace=wspace/w)
self.redraw()
###
#Updaters
def UpdateStatusBar(self, event):
if event.inaxes:
x, y = event.xdata, event.ydata
self.statusBar.SetStatusText(( "x= " + str(x) +
" y=" +str(y) ),
0)
#~ def UpdateMask(self):
#~ if self.data == None:
#~ return
#~
#~ self.data.mask = np.where(
#~ (self.data.time>=self.tRange[ 0])&(self.data.time<=self.tRange[ 1])&
#~ (self.data.azim>=self.azRange[0])&(self.data.azim<=self.azRange[1])&
#~ (self.data.elev>=self.elRange[0])&(self.data.elev<=self.elRange[1])&
#~ (self.data.cosa>=self.caRange[0])&(self.data.cosa<=self.caRange[1])&
#~ (self.data.cosb>=self.cbRange[0])&(self.data.cosb<=self.cbRange[1]) )[0]
def OffsetLimits(self,offset):
"""OffsetLimits(self,offset)
this comes up because sometimes you want the time from the second,
and sometimes you want the time from the trigger.
示例11: Chart
# 需要导入模块: from matplotlib.figure import Figure [as 别名]
# 或者: from matplotlib.figure.Figure import get_figwidth [as 别名]
#.........这里部分代码省略.........
"""
return self._plots
@property
def plot(self):
"""
First plot
@rtype: matplotlib.AxesSubplot
"""
return self._plots[0]
@property
def rows(self):
"""
Number of rows in this chart
@rtype: int
"""
return self._rows
@property
def columns(self):
"""
Number of columns in this chart
@rtype: int
"""
return self._columns
@property
def width(self):
"""
Chart's width in inches
@rtype: int
"""
return self._figure.get_figwidth()
@width.setter
def width(self, inches):
self._figure.set_figwidth(inches)
if self._backend_started:
self._backend.resize(self._figure)
@property
def height(self):
"""
Chart's height in inches
@rtype: int
"""
return self._figure.get_figheight()
@height.setter
def height(self, inches):
self._figure.set_figheight(inches)
if self._backend_started:
self._backend.resize(self._figure)
@property
def dpi(self):
"""
Chart's DPI
@rtype: int
"""
return self._figure.get_dpi()
@dpi.setter
def dpi(self, dpi):
self._figure.set_dpi(dpi)
self._backend.resize(self._figure)
@property
示例12: Viewer
# 需要导入模块: from matplotlib.figure import Figure [as 别名]
# 或者: from matplotlib.figure.Figure import get_figwidth [as 别名]
#.........这里部分代码省略.........
)
self.previous_button = tk.Button(master=buttonFrame,
text='Previous',
command=self.previous,
expand=None,
)
self.save_button = tk.Button(master=buttonFrame,
text='Save Image',
command=self.save,
expand=None,
)
self.eventstring = tk.StringVar()
self.eventstring.set("EventNum: {:05d}".format(self.event))
self.eventbox = tk.Label(master=buttonFrame,
textvariable=self.eventstring,
)
self.eventbox.pack(side=tk.LEFT)
self.previous_button.pack(side=tk.LEFT)
self.next_button.pack(side=tk.LEFT)
self.quit_button.pack(side=tk.RIGHT)
self.save_button.pack(side=tk.RIGHT)
self.infotext = tk.StringVar()
self.infotext.set("Click on a Pixel")
self.infobox = tk.Label(master=infoFrame, textvariable=self.infotext)
self.infobox.pack(side=tk.LEFT)
self.update()
tk.mainloop()
def init_plot(self):
self.width, self.height = self.fig.get_figwidth(), self.fig.get_figheight()
self.fig.clf()
self.ax = self.fig.add_subplot(1, 1, 1, aspect=1)
divider = make_axes_locatable(self.ax)
self.cax = divider.append_axes("right", size="5%", pad=0.1)
self.ax.set_axis_off()
if self.vmin is None:
vmin = np.min(self.dataset[self.event])
else:
vmin = self.vmin
if self.vmax is None:
vmax = np.max(self.dataset[self.event])
else:
vmax = self.vmax
if self.pixelset is None:
pixelset = np.zeros(1440, dtype=bool)
else:
pixelset = self.pixelset[self.event]
self.plot = self.ax.factcamera(
data=self.dataset[self.event],
pixelcoords=None,
cmap=self.cmap,
vmin=vmin,
vmax=vmax,
pixelset=pixelset,
pixelsetcolour=self.pixelsetcolour,
linewidth=None,
picker=False,
)
self.plot.set_picker(0)