本文整理汇总了Python中matplotlib.figure.Figure.get_figheight方法的典型用法代码示例。如果您正苦于以下问题:Python Figure.get_figheight方法的具体用法?Python Figure.get_figheight怎么用?Python Figure.get_figheight使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类matplotlib.figure.Figure
的用法示例。
在下文中一共展示了Figure.get_figheight方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: MatplotlibWidget
# 需要导入模块: from matplotlib.figure import Figure [as 别名]
# 或者: from matplotlib.figure.Figure import get_figheight [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: buildMetadataImage
# 需要导入模块: from matplotlib.figure import Figure [as 别名]
# 或者: from matplotlib.figure.Figure import get_figheight [as 别名]
def buildMetadataImage(self, layerInfoList, width):
"""
Creates the metadata caption for figures in the style used by WMSViz.
"""
self.metadataItems = self._buildMetadataItems(layerInfoList)
self.width = width
width=self.width;height=1600;dpi=100;transparent=False
figsize=(width / float(dpi), height / float(dpi))
fig = Figure(figsize=figsize, dpi=dpi, facecolor='w', frameon=(not transparent))
axes = fig.add_axes([0.04, 0.04, 0.92, 0.92], frameon=True,xticks=[], yticks=[])
renderer = Renderer(fig.dpi)
title, titleHeight = self._drawTitleToAxes(axes, renderer)
txt, textHeight = self._drawMetadataTextToAxes(axes, renderer, self.metadataItems)
# fit the axis round the text
pos = axes.get_position()
newpos = Bbox( [[pos.x0, pos.y1 - (titleHeight + textHeight) / height], [pos.x1, pos.y1]] )
axes.set_position(newpos )
# position the text below the title
newAxisHeight = (newpos.y1 - newpos.y0) * height
txt.set_position( (0.02, 0.98 - (titleHeight/newAxisHeight) ))
for loc, spine in axes.spines.iteritems():
spine.set_edgecolor(borderColor)
# Draw heading box
headingBoxHeight = titleHeight - 1
axes.add_patch(Rectangle((0, 1.0 - (headingBoxHeight/newAxisHeight)), 1, (headingBoxHeight/newAxisHeight),
facecolor=borderColor,
fill = True,
linewidth=0))
# reduce the figure height
originalHeight = fig.get_figheight()
pos = axes.get_position()
topBound = 20 / float(dpi)
textHeight = (pos.y1 - pos.y0) * originalHeight
newHeight = topBound * 2 + textHeight
# work out the new proportions for the figure
border = topBound / float(newHeight)
newpos = Bbox( [[pos.x0, border], [pos.x1, 1 - border]] )
axes.set_position(newpos )
fig.set_figheight(newHeight)
return image_util.figureToImage(fig)
示例3: MatplotlibWidget
# 需要导入模块: from matplotlib.figure import Figure [as 别名]
# 或者: from matplotlib.figure.Figure import get_figheight [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()
示例4: _
# 需要导入模块: from matplotlib.figure import Figure [as 别名]
# 或者: from matplotlib.figure.Figure import get_figheight [as 别名]
#.........这里部分代码省略.........
# top of the uppermost plot and the bottom of the lowest
# plot.
self.cb_ax = self.fig.add_axes(self.get_cb_axes())
self.fig.colorbar(
im,
cax=self.cb_ax,
orientation="vertical",
ticks=self.image_defs["y_labels"],
format=P.FuncFormatter(eval("self." + self.image_defs["formatter"])),
)
# print self.image_defs['y_labels']
for t in self.cb_ax.get_yticklabels():
t.set_fontsize(colorbar_fontsize)
canvas = FigureCanvasGTK3Agg(self.fig)
self.fig.canvas.mpl_connect("draw_event", self.on_draw)
canvas.show()
if save_file:
self.save_plot(canvas, save_file)
# todo this ought to a command line param
if not self.run_quietly:
dia = VOAPlotWindow("pythonProp - " + self.image_defs["title"], canvas, parent=parent)
return
def on_draw(self, event):
top = self.fig.subplotpars.top
bottom = self.fig.subplotpars.bottom
hspace = self.fig.subplotpars.hspace
wspace = self.fig.subplotpars.wspace
fig_height = self.fig.get_figheight()
needs_adjusting = False
# Area required at the top of the plot (Main title and subplot title)
bbox = self.subplot_title_label.get_window_extent()
subplot_title_bbox = bbox.inverse_transformed(self.fig.transFigure)
bbox = self.main_title_label.get_window_extent()
main_title_bbox = bbox.inverse_transformed(self.fig.transFigure)
_preferred_top_space = 1.25 * (subplot_title_bbox.height + main_title_bbox.height)
_actual_top_space = 1 - top
if (_actual_top_space < _preferred_top_space) or ((_actual_top_space - _preferred_top_space) > 0.11):
top = 0.99 - _preferred_top_space
needs_adjusting = True
if needs_adjusting:
self.fig.subplots_adjust(top=top, bottom=bottom, hspace=hspace, wspace=wspace)
self.cb_ax.set_position(self.get_cb_axes())
self.fig.canvas.draw()
return False
def save_plot(self, canvas, filename=None):
canvas.print_figure(filename, dpi=self.dpi, facecolor=self.fig.get_facecolor(), edgecolor="none")
def get_cb_axes(self):
bbox = self.subplots[0].get_window_extent()
axis_upper_y = bbox.inverse_transformed(self.fig.transFigure).ymax
bbox = self.subplots[-1].get_window_extent()
axis_lower_y = bbox.inverse_transformed(self.fig.transFigure).ymin
return [0.87, axis_lower_y, 0.02, axis_upper_y - axis_lower_y]
示例5: MatplotlibWidget
# 需要导入模块: from matplotlib.figure import Figure [as 别名]
# 或者: from matplotlib.figure.Figure import get_figheight [as 别名]
#.........这里部分代码省略.........
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):
return QSize(100, 100)
示例6: BrowserMatPlotFrame
# 需要导入模块: from matplotlib.figure import Figure [as 别名]
# 或者: from matplotlib.figure.Figure import get_figheight [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()
#.........这里部分代码省略.........
示例7: PlotterWidget
# 需要导入模块: from matplotlib.figure import Figure [as 别名]
# 或者: from matplotlib.figure.Figure import get_figheight [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
示例8: MatplotlibWidget
# 需要导入模块: from matplotlib.figure import Figure [as 别名]
# 或者: from matplotlib.figure.Figure import get_figheight [as 别名]
class MatplotlibWidget(FigureCanvas):
def __init__(self, parent=None):
settings = QtCore.QSettings("MBBH", "RISK")
self.ScreenDPI = int(settings.value('ScreenDPI','80'))
self.figure = Figure(dpi=self.ScreenDPI)
self.axes = self.figure.add_axes([0.1,0.1,0.8,0.8],frame_on=False,xticks=[],yticks=[])
FigureCanvas.__init__(self, self.figure)
self.setParent(parent)
def Plot(self):
if self.vg!=None:
self.vg.draw_voronoi(self.axes)
self.draw()
def resizeEvent(self,event):
height = self.size().height()/float(self.ScreenDPI)
width = self.size().width()/float(self.ScreenDPI)
self.figure.set_size_inches(width,height,forward=True)
self.positionCBarEdits()
self.draw()
def mousePressEvent(self,event):
if self.zoomInActButton and self.zoomInActButton.isChecked():
height = self.figure.get_figheight()*self.figure.dpi
inLeft = self.leftAxes.bbox.contains(event.pos().x(),height-event.pos().y())
inRight = self.rightAxes.bbox.contains(event.pos().x(),height-event.pos().y())
if inLeft or inRight:
if self.rubberBand is None:
self.zoomOrigin = event.pos()
self.rubberBand = QtGui.QRubberBand(QtGui.QRubberBand.Rectangle, self)
rect = QtCore.QRect(self.zoomOrigin,QtCore.QSize())
self.rubberBand.setGeometry(rect)
pal = QtGui.QPalette()
pal.setBrush(QtGui.QPalette.Foreground, QtGui.QBrush(QtCore.Qt.green))
pal.setBrush(QtGui.QPalette.Base, QtGui.QBrush(QtCore.Qt.red))
pal.setBrush(QtGui.QPalette.Highlight, QtGui.QBrush(QtCore.Qt.red))
self.rubberBand.setPalette(pal)
self.rubberBand.show()
def mouseMoveEvent(self,event):
if self.zoomInActButton and self.zoomInActButton.isChecked():
if self.rubberBand is not None:
pos = event.pos()
#constrain to aspect ratio of figure, key off Y
deltaX = event.pos().x() - self.zoomOrigin.x()
deltaY = event.pos().y() - self.zoomOrigin.y()
scaleX = float(deltaY)*self.zoomAspect
newPos = QtCore.QPoint(self.zoomOrigin.x()-scaleX,pos.y())
self.zoomPos = newPos
self.rubberBand.setGeometry(QtCore.QRect(self.zoomOrigin, newPos).normalized())
def mouseReleaseEvent(self,event):
height = self.figure.get_figheight()*self.figure.dpi
if self.zoomInActButton and self.zoomInActButton.isChecked():
if self.rubberBand is not None:
pos = self.zoomPos
endInLeft = self.leftAxes.bbox.contains(pos.x(),height-pos.y())
endInRight = self.rightAxes.bbox.contains(pos.x(),height-pos.y())
if endInLeft or endInRight:
end = pos
start =self.zoomOrigin
self.isZoomed=True
invFigure = self.figure.transFigure.inverted()
start = invFigure.transform((start.x(),start.y()))
end = invFigure.transform((end.x(),end.y()))
#print start,end
self.zoomExtents=(end[0],end[1],start[0],start[1])
start2 = self.figure.transFigure.transform(start)
end2 = self.figure.transFigure.transform(end)
self.zoomFactor=float(self.rightAxes.get_window_extent().height)/abs(end2[1]-start2[1])
self.controller.statusBar().showMessage(str(self.zoomFactor))
else:
print 'not in Focus'
#reset instance variables
self.zoomInActButton.defaultAction().toggle()
self.rubberBand.hide()
self.rubberBand = None #reset rubberband
self.Plot()
def mouseDoubleClickEvent(self,event):
#handle addition of watchPoint
if self.watchPointButton and self.watchPointButton.isChecked() and len(self.availWatchID)>0:
newIcon=WatchPoint(self,self.availWatchID.pop())
image=newIcon.pixmap()
newIcon.move(event.x()-image.width()/2.,event.y()-image.height()/2)
newIcon.show()
pos = event.pos()
rinv = self.rightAxes.transData.inverted()
height = self.figure.get_figheight()*self.figure.dpi
pos2 = rinv.transform((pos.x(),height - pos.y()))
#.........这里部分代码省略.........
示例9: Frequency
# 需要导入模块: from matplotlib.figure import Figure [as 别名]
# 或者: from matplotlib.figure.Figure import get_figheight [as 别名]
#.........这里部分代码省略.........
self.subplot_title_label = ax.set_title(title_str)
# Add a colorbar on the right hand side, aligned with the
# top of the uppermost plot and the bottom of the lowest
# plot.
self.cb_ax = self.fig.add_axes(self.get_cb_axes())
self.fig.colorbar(im, cax=self.cb_ax,
orientation='vertical',
ticks=self.image_defs['y_labels'],
format = P.FuncFormatter(eval('self.'+self.image_defs['formatter'])))
#print self.image_defs['y_labels']
for t in self.cb_ax.get_yticklabels():
t.set_fontsize(colorbar_fontsize)
canvas = FigureCanvasGTKAgg(self.fig)
self.fig.canvas.mpl_connect('draw_event', self.on_draw)
canvas.show()
if save_file :
self.save_plot(canvas, save_file)
#todo this ought to a command line param
if not self.run_quietly:
dia = VOAPlotWindow('pythonProp - ' + self.image_defs['title'], canvas, parent=parent)
return
def on_draw(self, event):
top = self.fig.subplotpars.top
bottom = self.fig.subplotpars.bottom
hspace = self.fig.subplotpars.hspace
wspace = self.fig.subplotpars.wspace
fig_height = self.fig.get_figheight()
needs_adjusting = False
# Area required at the top of the plot (Main title and subplot title)
bbox = self.subplot_title_label.get_window_extent()
subplot_title_bbox = bbox.inverse_transformed(self.fig.transFigure)
bbox = self.main_title_label.get_window_extent()
main_title_bbox = bbox.inverse_transformed(self.fig.transFigure)
_preferred_top_space = 1.25*(subplot_title_bbox.height + main_title_bbox.height)
_actual_top_space = 1-top
if (_actual_top_space < _preferred_top_space) or ((_actual_top_space - _preferred_top_space)>0.11):
top = 0.99 - _preferred_top_space
needs_adjusting = True
if needs_adjusting:
self.fig.subplots_adjust(top = top, bottom = bottom, hspace = hspace, wspace = wspace)
self.cb_ax.set_position(self.get_cb_axes())
self.fig.canvas.draw()
return False
def save_plot(self, canvas, filename=None):
canvas.print_figure(filename, dpi=self.dpi, facecolor='white', edgecolor='white')
def get_cb_axes(self):
bbox = self.subplots[0].get_window_extent()
axis_upper_y = bbox.inverse_transformed(self.fig.transFigure).ymax
示例10: PlotPanel
# 需要导入模块: from matplotlib.figure import Figure [as 别名]
# 或者: from matplotlib.figure.Figure import get_figheight [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
#.........这里部分代码省略.........
示例11: VoronoiPlotWidget
# 需要导入模块: from matplotlib.figure import Figure [as 别名]
# 或者: from matplotlib.figure.Figure import get_figheight [as 别名]
class VoronoiPlotWidget(FigureCanvas):
def __init__(self, parent=None):
settings = QtCore.QSettings("MBBH", "RISK")
self.ScreenDPI = int(settings.value('ScreenDPI','80'))
self.figure = Figure(dpi=self.ScreenDPI)
self.axes = self.figure.add_axes([0.1,0.1,0.8,0.8],frame_on=False,xticks=[],yticks=[])
FigureCanvas.__init__(self, self.figure)
#self.figure.canvas.mpl_connect('pick_event',self.on_pick)
self.setParent(parent)
self.controller = None
self.vg=None
self.cell_from=-1
self.cell_to=-1
def show(self):
self.Plot()
def Plot(self):
if self.vg!=None:
self.axes.cla()
self.vg.draw_voronoi(self.axes)
self.draw()
def resizeEvent(self,event):
height = self.size().height()/float(self.ScreenDPI)
width = self.size().width()/float(self.ScreenDPI)
self.figure.set_size_inches(width,height,forward=True)
self.draw()
def pick(self,event,mouse_down):
win_pos = event.pos()
inv = self.axes.transData.inverted()
height = self.figure.get_figheight()*self.figure.dpi
mpl_pos = inv.transform((win_pos.x(),height - win_pos.y()))
#determine which if any cell was picked
for cell in self.vg.cells:
result = cell.contains(mpl_pos)
if result == True:
print 'found match in cell',cell.id
if self.controller.deployMode and mouse_down:
self.controller.placeTroops(cell)
elif mouse_down:
self.cell_from=cell.id
cell.color = (0.2,0.9,0.9)
for i in cell.neighbors:
self.vg.cells[i].color = (0.8,0.8,0.8)
elif cell.id in self.vg.cells[self.cell_from].neighbors:
self.cell_to = cell.id
cell.color = (0.2,0.9,0.9)
self.Plot()
return True
return False
def mousePressEvent(self,event):
self.pick(event,True)
def mouseReleaseEvent(self,event):
if self.pick(event,False):
self.controller.battle(self.cell_from,self.cell_to)
示例12: __init__
# 需要导入模块: from matplotlib.figure import Figure [as 别名]
# 或者: from matplotlib.figure.Figure import get_figheight [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")
#.........这里部分代码省略.........
示例13: PlotPanel
# 需要导入模块: from matplotlib.figure import Figure [as 别名]
# 或者: from matplotlib.figure.Figure import get_figheight [as 别名]
#.........这里部分代码省略.........
self.SetLimits(elRange=ylims, azRange=xlims)
#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,
示例14: Frequency
# 需要导入模块: from matplotlib.figure import Figure [as 别名]
# 或者: from matplotlib.figure.Figure import get_figheight [as 别名]
#.........这里部分代码省略.........
if self.number_of_subplots > 1:
self.cb_ax = self.fig.add_axes(self.get_cb_axes())
else:
divider = make_axes_locatable(ax)
self.cb_ax = divider.append_axes("right", size="5%", pad=0.05)
self.fig.colorbar(im, cax=self.cb_ax,
orientation='vertical',
ticks=self.image_defs['y_labels'],
format = FuncFormatter(eval('self.'+self.image_defs['formatter'])))
#print self.image_defs['y_labels']
for t in self.cb_ax.get_yticklabels():
t.set_fontsize(colorbar_fontsize)
#self.fig.tight_layout()
canvas = FigureCanvas(self.fig)
self.fig.canvas.mpl_connect('draw_event', self.on_draw)
canvas.show()
if save_file :
self.save_plot(canvas, save_file)
#todo this ought to a command line param
if not self.run_quietly:
dia = VOAPlotWindow('pythonProp - ' + self.image_defs['title'], canvas, parent=parent, datadir=self.datadir)
return
def on_draw(self, event):
top = self.fig.subplotpars.top
bottom = self.fig.subplotpars.bottom
hspace = self.fig.subplotpars.hspace
wspace = self.fig.subplotpars.wspace
fig_height = self.fig.get_figheight()
needs_adjusting = False
# Area required at the top of the plot (Main title and subplot title)
bbox = self.subplot_title_label.get_window_extent()
subplot_title_bbox = bbox.inverse_transformed(self.fig.transFigure)
bbox = self.main_title_label.get_window_extent()
main_title_bbox = bbox.inverse_transformed(self.fig.transFigure)
_preferred_top_space = 1.25*(subplot_title_bbox.height + main_title_bbox.height)
_actual_top_space = 1-top
if (_actual_top_space < _preferred_top_space) or ((_actual_top_space - _preferred_top_space)>0.11):
top = 0.99 - _preferred_top_space
needs_adjusting = True
if needs_adjusting:
self.fig.subplots_adjust(top = top, bottom = bottom, hspace = hspace, wspace = wspace)
self.cb_ax.set_position(self.get_cb_axes())
self.fig.canvas.draw()
return False
def save_plot(self, canvas, filename=None):
canvas.print_figure(filename, dpi=self.dpi, facecolor=self.fig.get_facecolor(), edgecolor='none')
def get_cb_axes(self):
bbox = self.subplots[0].get_window_extent()
axis_upper_y = bbox.inverse_transformed(self.fig.transFigure).ymax
bbox = self.subplots[-1].get_window_extent()
axis_lower_y = bbox.inverse_transformed(self.fig.transFigure).ymin
return [0.87, axis_lower_y, 0.02, axis_upper_y-axis_lower_y]
def percent_format(self, x, pos):
return '%(percent)3d%%' % {'percent':x*100}
def SNR_format(self, x, pos):
return '%3ddB' % x
def SDBW_format(self, x, pos):
return '%3ddBW' % x
"""
The values below are derived from material
presented at http://www.voacap.com/s-meter.html
"""
def SMETER_format(self, x, pos):
S_DICT = {-151.18:'S1', -145.15:'S2', -139.13:'S3', -133.11:'S4', -127.09:'S5', \
-121.07:'S6', -115.05:'S7', -109.03:'S8', -103.01:'S9', -93.01:'S9+10dB', \
-83.01:'S9+20dB', -73.01:'S9+30dB', -63.01:'S9+40dB', -53.01:'S9+50dB', -43.01:'S9+60dB'}
if x in S_DICT:
return '%s' % S_DICT[x]
#return _('%(value)ddBW (%(s_value)s)') %{'value':x, 's_value':S_DICT[x]}
else : return '%3d' % x
def frequency_format(self, x, pos):
return '%2dMHz' % x
def default_format(self, x, pos):
return '%d' % x
示例15: Chart
# 需要导入模块: from matplotlib.figure import Figure [as 别名]
# 或者: from matplotlib.figure.Figure import get_figheight [as 别名]
#.........这里部分代码省略.........
"""
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
def formats(self):
"""
Supported output file formats
@rtype: L{csb.core.enum}
"""
return self._formats
def show(self):
"""
Show the GUI window (non-blocking).
"""
if not self._hasgui:
self._backend.add(self._figure)