本文整理汇总了Python中matplotlib.figure.Figure.sca方法的典型用法代码示例。如果您正苦于以下问题:Python Figure.sca方法的具体用法?Python Figure.sca怎么用?Python Figure.sca使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类matplotlib.figure.Figure
的用法示例。
在下文中一共展示了Figure.sca方法的5个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: Plot
# 需要导入模块: from matplotlib.figure import Figure [as 别名]
# 或者: from matplotlib.figure.Figure import sca [as 别名]
class Plot(QtGui.QWidget):
def __init__(self, winTitle="plot", parent = None, flags = QtCore.Qt.WindowFlags(0)):
""" __init__(winTitle="plot", parent = None, flags = Qt.WindowFlags(0)): Construct a new plot widget.\n winTitle = Tab title.\n parent = Widget parent.\n flags = QWidget flags"""
QtGui.QWidget.__init__(self, parent, flags)
self.setWindowTitle(winTitle)
# Create matplotlib canvas
self.fig = Figure()
self.canvas = FigureCanvas(self.fig)
self.canvas.setParent(self)
# Get axes
self.axes = self.fig.add_subplot(111)
self.axesList = [self.axes]
self.axes.xaxis.set_ticks_position('bottom')
self.axes.spines['top'].set_color('none')
self.axes.yaxis.set_ticks_position('left')
self.axes.spines['right'].set_color('none')
# Setup layout
vbox = QtGui.QVBoxLayout()
vbox.addWidget(self.canvas)
self.setLayout(vbox)
# Active series
self.series = []
# Indicators
self.skip = False
self.legend = False
self.legPos = (1.0, 1.0)
self.legSiz = 14
self.grid = False
def plot(self, x, y, name=None):
""" plot(self, x, y, name=None): Plot a new line and return it.\n x = X values\n y = Y values\n name = Serie name (for legend). """
l = Line(self.axes, x, y, name)
self.series.append(l)
# Update window
self.update()
return l
def update(self):
""" update(): Updates plot. """
if not self.skip:
self.skip = True
if self.legend:
legend(self.legend)
self.canvas.draw()
self.skip = False
def isGrid(self):
""" isGrid(): Return True if Grid is active, False otherwise. """
return bool(self.grid)
def isLegend(self):
""" isLegend(): Return True if Legend is active, False otherwise. """
return bool(self.legend)
def setActiveAxes(self, index):
""" setActiveAxes(index): Change current active axes.\n index = Index of the new active axes. """
self.axes = self.axesList[index]
self.fig.sca(self.axes)
示例2: Plot
# 需要导入模块: from matplotlib.figure import Figure [as 别名]
# 或者: from matplotlib.figure.Figure import sca [as 别名]
class Plot(PySide.QtGui.QWidget):
def __init__(self,
winTitle="plot",
parent=None,
flags=PySide.QtCore.Qt.WindowFlags(0)):
"""Construct a new plot widget.
Keyword arguments:
winTitle -- Tab title.
parent -- Widget parent.
flags -- QWidget flags
"""
PySide.QtGui.QWidget.__init__(self, parent, flags)
self.setWindowTitle(winTitle)
# Create matplotlib canvas
self.fig = Figure()
self.canvas = FigureCanvas(self.fig)
self.canvas.setParent(self)
# Get axes
self.axes = self.fig.add_subplot(111)
self.axesList = [self.axes]
self.axes.xaxis.set_ticks_position('bottom')
self.axes.spines['top'].set_color('none')
self.axes.yaxis.set_ticks_position('left')
self.axes.spines['right'].set_color('none')
# Add the navigation toolbar by default
self.mpl_toolbar = NavigationToolbar(self.canvas, self)
# Setup layout
vbox = PySide.QtGui.QVBoxLayout()
vbox.addWidget(self.canvas)
vbox.addWidget(self.mpl_toolbar)
self.setLayout(vbox)
# Active series
self.series = []
# Indicators
self.skip = False
self.legend = False
self.legPos = (1.0, 1.0)
self.legSiz = 14
self.grid = False
def plot(self, x, y, name=None):
"""Plot a new line and return it.
Keyword arguments:
x -- X values
y -- Y values
name -- Serie name (for legend). """
l = Line(self.axes, x, y, name)
self.series.append(l)
# Update window
self.update()
return l
def update(self):
"""Update the plot, redrawing the canvas."""
if not self.skip:
self.skip = True
if self.legend:
legend(self.legend, self.legPos, self.legSiz)
self.canvas.draw()
self.skip = False
def isGrid(self):
"""Return True if Grid is active, False otherwise."""
return bool(self.grid)
def isLegend(self):
"""Return True if Legend is active, False otherwise."""
return bool(self.legend)
def setActiveAxes(self, index):
"""Change the current active axes.
Keyword arguments:
index -- Index of the new active axes set.
"""
self.axes = self.axesList[index]
self.fig.sca(self.axes)
示例3: BackendMPL
# 需要导入模块: from matplotlib.figure import Figure [as 别名]
# 或者: from matplotlib.figure.Figure import sca [as 别名]
class BackendMPL(FigureCanvas, Backend):
"""matplotlib backend"""
_signalRedisplay = QtCore.pyqtSignal() # PyQt binds it to instances
def __init__(self, plot, parent=None, **kwargs):
Backend.__init__(self, plot)
self.fig = Figure()
self.fig.set_facecolor('w')
FigureCanvas.__init__(self, self.fig)
FigureCanvas.setSizePolicy(self,
QtGui.QSizePolicy.Expanding,
QtGui.QSizePolicy.Expanding)
self._items = {} # Mapping: plot item -> matplotlib item
# Set-up axes
leftAxes = self.fig.add_axes([.15, .15, .75, .75], label="left")
rightAxes = leftAxes.twinx()
rightAxes.set_label("right")
# critical for picking!!!!
rightAxes.set_zorder(0)
rightAxes.set_autoscaley_on(True)
leftAxes.set_zorder(1)
# this works but the figure color is left
leftAxes.set_axis_bgcolor('none')
self.fig.sca(leftAxes)
self._axes = {self.plot.axes.left: leftAxes,
self.plot.axes.right: rightAxes}
# Sync matplotlib and plot axes
for plotAxes, mplAxes in self._axes.items():
self._syncAxes(mplAxes, plotAxes)
# TODO sync all the plot items to support backend switch !
# Set-up events
self.fig.canvas.mpl_connect('button_press_event',
self.onMousePressed)
self.fig.canvas.mpl_connect('button_release_event',
self.onMouseReleased)
self.fig.canvas.mpl_connect('motion_notify_event',
self.onMouseMoved)
self.fig.canvas.mpl_connect('scroll_event',
self.onMouseWheel)
# Connect draw to redisplay
self._signalRedisplay.connect(
self.draw, QtCore.Qt.QueuedConnection)
@staticmethod
def _syncAxes(mplAxes, plotAxes):
"""Sync matplotlib Axes with the plot Axes"""
mplAxes.set_xlabel(plotAxes.xlabel)
mplAxes.set_xlim(plotAxes.xlimits)
mplAxes.set_xscale(plotAxes.xscale)
mplAxes.set_ylabel(plotAxes.ylabel)
mplAxes.set_ylim(plotAxes.ylimits)
mplAxes.set_yscale(plotAxes.yscale)
def triggerRedisplay(self):
self._signalRedisplay.emit()
def draw(self):
# Apply all modifications before redraw
for change in self._changes:
if change['event'] == 'addItem':
self._addItem(change['source'], change['item'])
elif change['event'] == 'removeItem':
self._removeItem(change)
elif change['event'] == 'set':
self._setAttr(
change['source'], change['attr'], change['value'])
else:
logger.warning('Unhandled event %s' % change['event'])
Backend.draw(self)
FigureCanvas.draw(self)
def onMousePressed(self, event):
pass # TODO
def onMouseMoved(self, event):
pass # TODO
def onMouseReleased(self, event):
pass # TODO
def onMouseWheel(self, event):
pass # TODO
def _addItem(self, axes, item):
mplAxes = self._axes[axes]
if isinstance(item, items.Curve):
#.........这里部分代码省略.........
示例4: BackendMatplotlib
# 需要导入模块: from matplotlib.figure import Figure [as 别名]
# 或者: from matplotlib.figure.Figure import sca [as 别名]
class BackendMatplotlib(BackendBase.BackendBase):
"""Base class for Matplotlib backend without a FigureCanvas.
For interactive on screen plot, see :class:`BackendMatplotlibQt`.
See :class:`BackendBase.BackendBase` for public API documentation.
"""
def __init__(self, plot, parent=None):
super(BackendMatplotlib, self).__init__(plot, parent)
# matplotlib is handling keep aspect ratio at draw time
# When keep aspect ratio is on, and one changes the limits and
# ask them *before* next draw has been performed he will get the
# limits without applying keep aspect ratio.
# This attribute is used to ensure consistent values returned
# when getting the limits at the expense of a replot
self._dirtyLimits = True
self.fig = Figure()
self.fig.set_facecolor("w")
self.ax = self.fig.add_axes([.15, .15, .75, .75], label="left")
self.ax2 = self.ax.twinx()
self.ax2.set_label("right")
# critical for picking!!!!
self.ax2.set_zorder(0)
self.ax2.set_autoscaley_on(True)
self.ax.set_zorder(1)
# this works but the figure color is left
self.ax.set_axis_bgcolor('none')
self.fig.sca(self.ax)
self._overlays = set()
self._background = None
self._colormaps = {}
self._graphCursor = tuple()
self.matplotlibVersion = matplotlib.__version__
self.setGraphXLimits(0., 100.)
self.setGraphYLimits(0., 100., axis='right')
self.setGraphYLimits(0., 100., axis='left')
self._enableAxis('right', False)
# Add methods
def addCurve(self, x, y, legend,
color, symbol, linewidth, linestyle,
yaxis,
xerror, yerror, z, selectable,
fill):
for parameter in (x, y, legend, color, symbol, linewidth, linestyle,
yaxis, z, selectable, fill):
assert parameter is not None
assert yaxis in ('left', 'right')
if (len(color) == 4 and
type(color[3]) in [type(1), numpy.uint8, numpy.int8]):
color = numpy.array(color, dtype=numpy.float) / 255.
if yaxis == "right":
axes = self.ax2
self._enableAxis("right", True)
else:
axes = self.ax
picker = 3 if selectable else None
artists = [] # All the artists composing the curve
# First add errorbars if any so they are behind the curve
if xerror is not None or yerror is not None:
if hasattr(color, 'dtype') and len(color) == len(x):
errorbarColor = 'k'
else:
errorbarColor = color
# On Debian 7 at least, Nx1 array yerr does not seems supported
if (yerror is not None and yerror.ndim == 2 and
yerror.shape[1] == 1 and len(x) != 1):
yerror = numpy.ravel(yerror)
errorbars = axes.errorbar(x, y, label=legend,
xerr=xerror, yerr=yerror,
linestyle=' ', color=errorbarColor)
artists += list(errorbars.get_children())
if hasattr(color, 'dtype') and len(color) == len(x):
# scatter plot
if color.dtype not in [numpy.float32, numpy.float]:
actualColor = color / 255.
else:
actualColor = color
if linestyle not in ["", " ", None]:
# scatter plot with an actual line ...
#.........这里部分代码省略.........
示例5: BackendMatplotlib
# 需要导入模块: from matplotlib.figure import Figure [as 别名]
# 或者: from matplotlib.figure.Figure import sca [as 别名]
class BackendMatplotlib(BackendBase.BackendBase):
"""Base class for Matplotlib backend without a FigureCanvas.
For interactive on screen plot, see :class:`BackendMatplotlibQt`.
See :class:`BackendBase.BackendBase` for public API documentation.
"""
def __init__(self, plot, parent=None):
super(BackendMatplotlib, self).__init__(plot, parent)
# matplotlib is handling keep aspect ratio at draw time
# When keep aspect ratio is on, and one changes the limits and
# ask them *before* next draw has been performed he will get the
# limits without applying keep aspect ratio.
# This attribute is used to ensure consistent values returned
# when getting the limits at the expense of a replot
self._dirtyLimits = True
self._axesDisplayed = True
self._matplotlibVersion = _parse_version(matplotlib.__version__)
self.fig = Figure()
self.fig.set_facecolor("w")
self.ax = self.fig.add_axes([.15, .15, .75, .75], label="left")
self.ax2 = self.ax.twinx()
self.ax2.set_label("right")
# disable the use of offsets
try:
self.ax.get_yaxis().get_major_formatter().set_useOffset(False)
self.ax.get_xaxis().get_major_formatter().set_useOffset(False)
self.ax2.get_yaxis().get_major_formatter().set_useOffset(False)
self.ax2.get_xaxis().get_major_formatter().set_useOffset(False)
except:
_logger.warning('Cannot disabled axes offsets in %s '
% matplotlib.__version__)
# critical for picking!!!!
self.ax2.set_zorder(0)
self.ax2.set_autoscaley_on(True)
self.ax.set_zorder(1)
# this works but the figure color is left
if self._matplotlibVersion < _parse_version('2'):
self.ax.set_axis_bgcolor('none')
else:
self.ax.set_facecolor('none')
self.fig.sca(self.ax)
self._overlays = set()
self._background = None
self._colormaps = {}
self._graphCursor = tuple()
self._enableAxis('right', False)
self._isXAxisTimeSeries = False
# Add methods
def addCurve(self, x, y, legend,
color, symbol, linewidth, linestyle,
yaxis,
xerror, yerror, z, selectable,
fill, alpha, symbolsize):
for parameter in (x, y, legend, color, symbol, linewidth, linestyle,
yaxis, z, selectable, fill, alpha, symbolsize):
assert parameter is not None
assert yaxis in ('left', 'right')
if (len(color) == 4 and
type(color[3]) in [type(1), numpy.uint8, numpy.int8]):
color = numpy.array(color, dtype=numpy.float) / 255.
if yaxis == "right":
axes = self.ax2
self._enableAxis("right", True)
else:
axes = self.ax
picker = 3 if selectable else None
artists = [] # All the artists composing the curve
# First add errorbars if any so they are behind the curve
if xerror is not None or yerror is not None:
if hasattr(color, 'dtype') and len(color) == len(x):
errorbarColor = 'k'
else:
errorbarColor = color
# On Debian 7 at least, Nx1 array yerr does not seems supported
if (isinstance(yerror, numpy.ndarray) and yerror.ndim == 2 and
yerror.shape[1] == 1 and len(x) != 1):
yerror = numpy.ravel(yerror)
errorbars = axes.errorbar(x, y, label=legend,
xerr=xerror, yerr=yerror,
linestyle=' ', color=errorbarColor)
#.........这里部分代码省略.........