本文整理汇总了Python中matplotlib.figure.Figure.delaxes方法的典型用法代码示例。如果您正苦于以下问题:Python Figure.delaxes方法的具体用法?Python Figure.delaxes怎么用?Python Figure.delaxes使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类matplotlib.figure.Figure
的用法示例。
在下文中一共展示了Figure.delaxes方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: MplCanvas
# 需要导入模块: from matplotlib.figure import Figure [as 别名]
# 或者: from matplotlib.figure.Figure import delaxes [as 别名]
class MplCanvas(FigureCanvasQTAgg, customthreads.StoppableThread):
def __init__(self, parent=None, width=5, height=4, channel=1,
dpi=100, *args, **kwargs):
customthreads.StoppableThread.__init__(self, *args, **kwargs)
self.in_queue = queue.Queue()
self.fig = Figure(figsize=(width, height), dpi=dpi)
FigureCanvasQTAgg.__init__(self, self.fig)
FigureCanvasQTAgg.setSizePolicy(self,
QtWidgets.QSizePolicy.Expanding,
QtWidgets.QSizePolicy.Expanding)
FigureCanvasQTAgg.updateGeometry(self)
self.axes_list = []
self.ylim = None
self.setParent(parent)
self.set_channel(channel)
# self.axes = self.fig.add_subplot(111)
# self.axes.hold(False)
def set_channel(self, channel):
self.channel = channel
'''clear subplots'''
if(self.axes_list is not []):
for ax in self.axes_list:
self.fig.delaxes(ax)
self.axes_list = []
for i in range(1, self.channel+1):
self.axes_list.append(self.fig.add_subplot(self.channel, 1, i))
for ax in self.axes_list:
ax.hold(False)
def set_lim(self, dtype):
self.typeinfo = numpy.iinfo(dtype)
self.ylim = [self.typeinfo.min, self.typeinfo.max]
def split_channel(self, data):
return numpy.transpose(numpy.reshape(data, (len(data)/self.channel, self.channel)))
def run(self):
'''Thread Loop'''
while(self.is_stopped() is False):
try:
data = self.in_queue.get_nowait()
split_data = self.split_channel(data)
for i in range(self.channel):
# print(split_data[i], len(split_data[i]))
self.axes_list[i].plot(range(len(split_data[i])), split_data[i], 'b')
self.axes_list[i].set_ylim(self.ylim)
self.draw()
except queue.Empty:
'''do nothing'''
pass
示例2: CutePlot
# 需要导入模块: from matplotlib.figure import Figure [as 别名]
# 或者: from matplotlib.figure.Figure import delaxes [as 别名]
#.........这里部分代码省略.........
else:
self.trunc_logy()
# Log-log plot
else:
if not self.trunc_cb.isChecked():
self.add_main()
self.axes.loglog(self.input_x,self.y,self.plot_symbol)
else:
self.trunc_loglog()
# Add grid if grid checkbox is checked
if self.axis_state == 0:
self.axes.grid(self.grid_cb.isChecked())
else:
if hasattr(self, 'axes_Q1'):
self.axes_Q1.grid(self.grid_cb.isChecked())
if hasattr(self, 'axes_Q2'):
self.axes_Q2.grid(self.grid_cb.isChecked())
if hasattr(self, 'axes_Q3'):
self.axes_Q3.grid(self.grid_cb.isChecked())
if hasattr(self, 'axes_Q4'):
self.axes_Q4.grid(self.grid_cb.isChecked())
self.axes.set_xlabel('$x$')
self.axes.set_ylabel('$f(x)$')
self.canvas.draw()
self.guardarImagen()
def remove_subplots(self):
# Remove all subplots and axis flip flags
if hasattr(self, 'axes_Q1'):
self.fig.delaxes(self.axes_Q1)
del self.axes_Q1
if hasattr(self, 'axes_Q2'):
self.fig.delaxes(self.axes_Q2)
del self.axes_Q2
if hasattr(self, 'flip_Q2'):
del self.flip_Q2
if hasattr(self, 'axes_Q3'):
self.fig.delaxes(self.axes_Q3)
del self.axes_Q3
del self.flip_Q3
if hasattr(self, 'axes_Q4'):
self.fig.delaxes(self.axes_Q4)
del self.axes_Q4
if hasattr(self, 'flip_Q4'):
del self.flip_Q4
def add_main(self):
# Reinsert the main plot
if self.axis_state > 0:
self.remove_subplots()
self.axes = self.fig.add_subplot(111)
self.axis_state = 0
def create_menu(self):
exitAction = QAction('Quit', self)
exitAction.setShortcut('Ctrl+Q')
exitAction.setStatusTip('Exit application')
exitAction.triggered.connect(self.close)
menubar = self.menuBar()
fileMenu = menubar.addMenu('&File')
示例3: MainWindow
# 需要导入模块: from matplotlib.figure import Figure [as 别名]
# 或者: from matplotlib.figure.Figure import delaxes [as 别名]
#.........这里部分代码省略.........
self.mainLayout.addLayout(leftLayout)
rightLayout = QtGui.QVBoxLayout()
rightLayout.addWidget(self.canvas)
rightLayout.addWidget(self.mpl_toolbar)
self.mainLayout.addLayout(rightLayout)
self.main_widget = QtGui.QWidget()
self.main_widget.setLayout(self.mainLayout)
self.setCentralWidget(self.main_widget)
self.setWindowTitle('Main App')
self.setMinimumSize(1200, 700)
self.files = None
# ファイルをロードするためのメソッド
def open_folder(self):
fname = QtGui.QFileDialog.getExistingDirectory(self, 'Open Directory', os.path.expanduser('~' + '/research/Musics'))
files = glob.glob(str(fname) + '/*')
self.fname = fname
self.files = files
musics = load_data(files)
self.musics = musics
self.label2.setText('opened folder: ' + fname)
self.statusBar().showMessage('opened ' + fname + ' successfully')
# 多次元尺度構成法 (MDS) によるプロットを行うメソッド
def plot_mds(self, labels, data):
leds = [ 'cluster ' + str(i) for i in xrange(self.k) ]
pt = ['o', '+', 'x', '4']
mds = manifold.MDS(n_components=2, dissimilarity='euclidean')
y = mds.fit_transform(data)
self.fig.delaxes(self.fig.axes[0])
self.axes = self.fig.add_axes([0.1, 0.1, 0.8, 0.8])
for i in xrange(self.k):
dat = y[np.where(labels==i)]
self.axes.plot(dat[:, 0], dat[:, 1], pt[i/6], label=leds[i])
self.axes.set_xlim(np.min(y[:, 0]) - 0.5, np.max(y[:, 0]) + 1.5)
self.axes.set_ylim(np.min(y[:, 1]) - 0.5, np.max(y[:, 1]) + 1.5)
self.axes.set_title('MDS Scatter Plots')
self.axes.legend(loc='upper right', fontsize='x-small')
self.canvas.draw()
# 感情スコアをプロットするメソッド
@QtCore.pyqtSlot(QtCore.QModelIndex)
def plot_a_score(self, index):
checked = self.mode_select.checkedId()
if checked == 1: return
props = [
'ecstasy', 'admiration', 'terror', 'amazement',
'grief', 'loathing', 'rage', 'vigilance',
]
self.fig.delaxes(self.fig.axes[0])
self.axes = self.fig.add_axes([0.1, 0.05, 0.8, 0.8], polar=True)
cols = [
'yellow', 'lime', 'darkgreen', 'cyan',
'blue', 'magenta', 'red', 'orange',
]
theta = np.pi/2 - np.arange(0.0, 2*np.pi, 2*np.pi/8) - np.pi/16
score = self.clusters[self.selected_cluster][index.row()].score
width = np.pi/8 * np.ones(8)
bars = self.axes.bar(theta, score, width=width, bottom=0.0)
示例4: Qt4MplCanvas
# 需要导入模块: from matplotlib.figure import Figure [as 别名]
# 或者: from matplotlib.figure.Figure import delaxes [as 别名]
#.........这里部分代码省略.........
print "[Error] Plot %s is not in axes.lines which has %d lines. Error mesage: %s" % (
str(plot), len(self.axes.lines), str(e))
self._lineDict[ikey] = None
else:
# error bar
plot[0].remove()
for line in plot[1]:
line.remove()
for line in plot[2]:
line.remove()
self._lineDict[ikey] = None
# ENDIF(plot)
# ENDFOR
self._setupLegend()
self.draw()
return
def clear_canvas(self):
""" Clear data including lines and image from canvas
"""
# clear the image for next operation
self.axes.hold(False)
# Clear all lines
self.clear_all_1d_plots()
# clear image
self.axes.cla()
# Try to clear the color bar
if len(self.fig.axes) > 1:
self.fig.delaxes(self.fig.axes[1])
self._colorBar = None
# This clears the space claimed by color bar but destroys sub_plot too.
self.fig.clear()
# Re-create subplot
self.axes = self.fig.add_subplot(111)
# flush/commit
self._flush()
return
def getLastPlotIndexKey(self):
""" Get the index/key of the last added line
"""
return self._lineIndex-1
def getPlot(self):
""" reture figure's axes to expose the matplotlib figure to PyQt client
"""
return self.axes
def getXLimit(self):
""" Get limit of Y-axis
"""
return self.axes.get_xlim()
def getYLimit(self):
""" Get limit of Y-axis
"""
return self.axes.get_ylim()
示例5: DensityPanel
# 需要导入模块: from matplotlib.figure import Figure [as 别名]
# 或者: from matplotlib.figure.Figure import delaxes [as 别名]
class DensityPanel(FigureCanvasWxAgg):
def __init__(self, parent, **kwargs):
self.figure = Figure()
FigureCanvasWxAgg.__init__(self, parent, -1, self.figure, **kwargs)
self.canvas = self.figure.canvas
self.SetMinSize((100,100))
self.figure.set_facecolor((1,1,1))
self.figure.set_edgecolor((1,1,1))
self.canvas.SetBackgroundColour('white')
self.subplot = self.figure.add_subplot(111)
self.gate_helper = GatingHelper(self.subplot, self)
self.navtoolbar = None
self.point_list = []
self.gridsize = 50
self.cb = None
self.x_scale = LINEAR_SCALE
self.y_scale = LINEAR_SCALE
self.color_scale = None
self.x_label = ''
self.y_label = ''
self.cmap ='jet'
self.canvas.mpl_connect('button_release_event', self.on_release)
def setpointslists(self, points):
self.subplot.clear()
self.point_list = points
plot_pts = np.array(points).astype(float)
if self.x_scale == LOG_SCALE:
plot_pts = plot_pts[(plot_pts[:,0]>0)]
if self.y_scale == LOG_SCALE:
plot_pts = plot_pts[(plot_pts[:,1]>0)]
hb = self.subplot.hexbin(plot_pts[:, 0], plot_pts[:, 1],
gridsize=self.gridsize,
xscale=self.x_scale,
yscale=self.y_scale,
bins=self.color_scale,
cmap=matplotlib.cm.get_cmap(self.cmap))
if self.cb:
# Remove the existing colorbar and reclaim the space so when we add
# a colorbar to the new hexbin subplot, it doesn't get indented.
self.figure.delaxes(self.figure.axes[1])
self.figure.subplots_adjust(right=0.90)
self.cb = self.figure.colorbar(hb)
if self.color_scale==LOG_SCALE:
self.cb.set_label('log10(N)')
self.subplot.set_xlabel(self.x_label)
self.subplot.set_ylabel(self.y_label)
xmin = np.nanmin(plot_pts[:,0])
xmax = np.nanmax(plot_pts[:,0])
ymin = np.nanmin(plot_pts[:,1])
ymax = np.nanmax(plot_pts[:,1])
# Pad all sides
if self.x_scale==LOG_SCALE:
xmin = xmin/1.5
xmax = xmax*1.5
else:
xmin = xmin-(xmax-xmin)/20.
xmax = xmax+(xmax-xmin)/20.
if self.y_scale==LOG_SCALE:
ymin = ymin/1.5
ymax = ymax*1.5
else:
ymin = ymin-(ymax-ymin)/20.
ymax = ymax+(ymax-ymin)/20.
self.subplot.axis([xmin, xmax, ymin, ymax])
self.reset_toolbar()
def getpointslists(self):
return self.point_list
def setgridsize(self, gridsize):
self.gridsize = gridsize
def set_x_scale(self, scale):
self.x_scale = scale
def set_y_scale(self, scale):
self.y_scale = scale
def set_color_scale(self, scale):
if scale==LINEAR_SCALE:
scale = None
self.color_scale = scale
def set_x_label(self, label):
self.x_label = label
def set_y_label(self, label):
self.y_label = label
#.........这里部分代码省略.........
示例6: __init__
# 需要导入模块: from matplotlib.figure import Figure [as 别名]
# 或者: from matplotlib.figure.Figure import delaxes [as 别名]
#.........这里部分代码省略.........
def polchkcall(self):
self.polchk = self.polarvar.get()
def setslice(self):
self.slicename=self.slvar.get()
if self.slicename == "Along x1" or self.slicename == "Along x2" or self.slicename == "Along x3":
self.surfbutton.config(state='disabled')
self.arrowchkb.config(state = 'disabled')
self.arrowvar.set(0)
self.chkb.config(state = 'disabled')
self.contvar.set(0)
self.pltbutton.config(state='active')
self.polchkb.config(state='disabled')
self.polarvar.set(0)
else:
self.pltbutton.config(state='disabled')
self.arrowchkb.config(state = 'normal')
self.chkb.config(state = 'normal')
self.surfbutton.config(state='active')
self.polchkb.config(state='normal')
if self.slicename == "Along x2-x3":
self.polchkb.config(state='disabled')
self.polarvar.set(0)
def plotclear(self):
self.a.clear()
if len(self.f.axes)>1:
self.f.delaxes(self.f.axes[1])
self.f.subplots_adjust(right=0.90)
self.canvas.show()
def plotfinal(self):
if self.getplotvar() == True:
self.a.axis([self.getxaxisrange()[0],self.getxaxisrange()[1],self.getvarrange()[0],self.getvarrange()[1]])
self.a.plot(self.x,self.var)
self.a.set_aspect('auto')
self.a.set_xlabel(self.xlb.get())
self.a.set_ylabel(self.ylb.get())
self.canvas.show()
def plotsurface(self):
tdum = time.time()
self.plotclear()
if self.preaspect.get() == 1:
self.a.set_aspect('equal')
else:
self.a.set_aspect('auto')
if self.polarvar.get() == 1:
if self.drawpolar() == True:
self.a.axis([self.getxaxisrange()[0],self.getxaxisrange()[1],self.getyaxisrange()[0],self.getyaxisrange()[1]])
self.image = self.a.imshow(self.SphData[self.myvar], origin='lower',extent=self.extent, interpolation='nearest',cmap="jet", vmin=self.getvarrange()[0],vmax=self.getvarrange()[1])
self.f.colorbar(self.image)
else:
if self.getsurfvar() == True:
self.a.axis([self.getxaxisrange()[0],self.getxaxisrange()[1],self.getyaxisrange()[0],self.getyaxisrange()[1]])
self.image=self.a.pcolormesh(self.x,self.y,self.var,cmap='jet',vmin=self.getvarrange()[0],vmax=self.getvarrange()[1])
示例7: GraphPanel
# 需要导入模块: from matplotlib.figure import Figure [as 别名]
# 或者: from matplotlib.figure.Figure import delaxes [as 别名]
class GraphPanel(wx.Panel):
"""Graph panel draws the runtime graph"""
def __init__(self,parent):
wx.Panel.__init__(self,parent)
self.SetBackgroundColour('#FFFFFF')
self.SetSizeWH(500,600)
self.initGraph()
wx.EVT_PAINT(self, self.OnPaint)
self.redraw_bars = False
self.brother = None
def drawSpans(self,FirstLoad=False):
""" draws interval spans"""
global lastTrialDuration
global newWaitDuration
startAt = self.trial-0.5
h= 1.0
if self.trial==1:
startAt=0
h=1.5
drawX = 0.0
del graphStartTimes[:]
for i in X.intervalList:
graphStartTimes.append(drawX)
color = uv.iColors[i.type]
if isinstance(i, Intervals.ToneInt):
color = uv.freq2color(i.freq)
self.axes.bar(drawX, h,
color=color,zorder=0,lw=0.0, width=i.duration, bottom=startAt,)
else:
self.axes.bar(drawX, h,
color=color,zorder=0,lw=0.0, width=i.duration, bottom=startAt,)
drawX+=i.duration #raj-changed the value from i.maxDuration to i.duration to make the graph change dynamically based on lever press
def initGraph(self):
""" initalize graph to draw spans """
self.trial = 1
self.sbs = {}
self.sbs['Lever'] = ScatterBrain('Lever','#3399FF','o')
self.sbs['Mark'] = ScatterBrain('Mark','#000000','x')
for i in range(0,5):
name = 'aTaste%d'%i
self.sbs[name] = ScatterBrain(name,uv.TasteColors[i],'s')
name2 = 'mTaste%d'%i
self.sbs[name2] = ScatterBrain(name2,uv.TasteColors[i],'s',False)
self.figure = Figure(dpi=100,figsize=(5,5.5))
self.axes = self.figure.add_subplot(111)
print 'X.trial', X.trialDuration
self.axes.axis([0,X.trialDuration,0,1.5])
self.axes.set_xlabel('time (s)')
self.drawSpans(True)
LText = FontProperties()
LText.set_size("small")
self.axes.legend((self.sbs['Lever'].getPlot(self.axes),self.sbs['Mark'].getPlot(self.axes),
self.sbs['aTaste1'].getPlot(self.axes),self.sbs['mTaste1'].getPlot(self.axes)),
("Lever Press","Time Marked", "Reward","Manual Reward"),
prop=LText, fancybox=True, bbox_to_anchor=(0., 1.02, 1., .102), loc=1, ncol=2, mode="expand", borderaxespad=0)
self.canvas = FigureCanvas(self, -1, self.figure)
def clearGraph(self):
""" clear graph"""
self.figure.delaxes(self.axes)
self.initGraph()
self.Refresh()
def addPoint(self,i,t,pcat):
""" add point to a scatter plot
Args:
i (int): index of intervals
t (float): time to point to
pcat (int): which scatter plot to add point to
"""
ti = t
if i!=-1:
ti+= graphStartTimes[i]
if pcat<8:
self.sbs['aTaste%d'%pcat].addPoint(ti,self.trial)
elif pcat<16:
self.sbs['mTaste%d'%(pcat-8)].addPoint(ti,self.trial)
elif pcat==30:
self.sbs['Lever'].addPoint(ti,self.trial)
elif pcat==31:
self.sbs['Mark'].addPoint(ti,self.trial)
#.........这里部分代码省略.........
示例8: PlotFrame
# 需要导入模块: from matplotlib.figure import Figure [as 别名]
# 或者: from matplotlib.figure.Figure import delaxes [as 别名]
#.........这里部分代码省略.........
self.theta = self.fileReader.getThetaValues(self.callRadio.GetValue(),
self.thetaCheck.IsChecked(), self.differenceCheck.IsChecked(), self.effectCheck.IsChecked())
self.rho = self.fileReader.getRhoValues(self.callRadio.GetValue(),
self.rhoCheck.IsChecked(), self.differenceCheck.IsChecked(), self.effectCheck.IsChecked())
self.risidual = self.fileReader.getRisidualValues(self.callRadio.GetValue(), self.risidualCheck.IsChecked(),
self.differenceCheck.IsChecked(), self.effectCheck.IsChecked())
self.Plot_Data()
def onStockSlider(self, event=None):
self.statusbar.SetStatusText("Stock price bump: "+str(self.stockSlider.GetValue()))
self.stock_bump = self.stockSlider.GetValue()-1
self.Plot_Data()
def onRateSlider(self, event=None):
self.statusbar.SetStatusText("Interest Rate bump: "+str(self.rateSlider.GetValue()))
self.rate_bump = self.rateSlider.GetValue()-1
self.Plot_Data()
def onVolatilSlider(self, event=None):
self.statusbar.SetStatusText("Volatility bump: "+str(self.volatilSlider.GetValue()))
self.volitile_bump = self.volatilSlider.GetValue()-1
self.Plot_Data()
def ontimeStepSlider(self, event=None):
self.statusbar.SetStatusText("Time step bump: "+str(self.timeStepSlider.GetValue()))
self.time_bump = self.timeStepSlider.GetValue()-1
self.Plot_Data()
self.Plot_Data()
""" Graph plotting methods """
def clearPlots(self):
""" Clear all graphs and plots for next draw """
for a in self.fig.axes:
self.fig.delaxes(a)
def Plotter_2D_general(self, axes):
# plot option price graph
temp_option_price = []
if len(self.option_price) > 0:
temp_option_price = numpy.array(map(float, self.option_price[self.stock_bump]))
if len(self.option_price) > 0:
axes.plot(self.time, self.option_price[self.stock_bump], color='black')
# stagger plot effects of greeks
temp_delta = []
temp_gamma = []
temp_theta = []
temp_rho = []
temp_risidual = []
if len(self.delta) > 0:
temp_delta = numpy.array(self.delta[self.stock_bump])
if len(self.gamma) > 0:
temp_gamma = numpy.array(self.gamma[self.stock_bump])
if len(self.rho) > 0:
temp_rho = numpy.array(self.rho[self.rate_bump])
if len(self.theta) > 0:
temp_theta = numpy.array(self.theta[self.time_bump])
if len(self.risidual) > 0:
temp_risidual = numpy.array(self.risidual[self.stock_bump])
if not self.differenceCheck.IsChecked() and len(temp_option_price) > 0:
for t in self.time:
greeks_below = []
greeks_above = [] # above/below option price
if t < 30:
# sort arrays
示例9: MplGraphQt5Widget
# 需要导入模块: from matplotlib.figure import Figure [as 别名]
# 或者: from matplotlib.figure.Figure import delaxes [as 别名]
class MplGraphQt5Widget(QWidget):
def __init__(self, parent=None):
super(MplGraphQt5Widget, self).__init__(parent)
self.width = 3
self.height = 3
self.dpi = 100
self._dataY = np.array([])
self._dataX = np.array([])
self._spCols = 1
self._spRows = 1
self.all_sp_axes = []
self.fig = Figure(figsize=(self.width, self.height), dpi=self.dpi)
self.all_sp_axes.append(self.fig.add_subplot(self._spCols, self._spRows, 1))
self.fig.set_frameon(False)
self.fig.set_tight_layout(True)
self.canvas = Canvas(self.fig)
self._navBarOn = False
self.mpl_toolbar = NavigationToolbar(self.canvas, parent)
self.mpl_toolbar.dynamic_update()
self.canvas.mpl_connect('key_press_event', self.on_key_press)
self.canvas.mpl_connect('button_press_event', self.on_button_press)
self.canvas.mpl_connect('motion_notify_event', self.on_mouse_move)
self.canvas.setFocusPolicy(Qt.ClickFocus)
self.canvas.setFocus()
self.canvas.setParent(parent)
self.canvas.clearMask()
self.canvas.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)
self.canvas.updateGeometry()
vbox = QVBoxLayout()
vbox.addWidget(self.canvas)
vbox.addWidget(self.mpl_toolbar)
if not self._navBarOn:
self.mpl_toolbar.hide()
self.setLayout(vbox)
def get_icon(name):
"""Return Matplotlib icon *name*"""
return QIcon(osp.join(rcParams['datapath'], 'images', name))
key_pressed = pyqtSignal(object, name='keyPressed')
def on_key_press(self, event):
self.key_pressed.emit(event)
key_press_handler(event, self.canvas, self.mpl_toolbar)
button_pressed = pyqtSignal(object, name='buttonPressed')
def on_button_press(self, event):
self.button_pressed.emit(event)
key_press_handler(event, self.canvas, self.mpl_toolbar)
mouse_move = pyqtSignal(object, name='mouseMoved')
def on_mouse_move(self, event):
self.mouse_move.emit(event)
key_press_handler(event, self.canvas, self.mpl_toolbar)
def generateNewAxes(self):
for ax in self.all_sp_axes:
self.fig.delaxes(ax)
self.all_sp_axes = []
numOfAxes = (self._spRows*self._spCols)+1
for i in np.arange(1,numOfAxes):
self.all_sp_axes.append(self.fig.add_subplot(self._spRows, self._spCols, i))
self.canvas.setGeometry(100, 100, 300, 300) #Used to update the new number of axes
self.canvas.updateGeometry() #This will bring the size of the canvas back to the original (defined by the vbox)
spRowsChanged = pyqtSignal(int)
def getspRows(self):
return self._spRows
@pyqtSlot(int)
def setspRows(self, spRows):
self._spRows = spRows
self.generateNewAxes()
self.spRowsChanged.emit(spRows)
def resetspRows(self):
self.setspRows(1)
spRows = pyqtProperty(int, getspRows, setspRows, resetspRows)
spColsChanged = pyqtSignal(int)
def getspCols(self):
return self._spCols
#.........这里部分代码省略.........
示例10: LPlotWidget
# 需要导入模块: from matplotlib.figure import Figure [as 别名]
# 或者: from matplotlib.figure.Figure import delaxes [as 别名]
#.........这里部分代码省略.........
#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
@pyqtSlot()
def clear(self):
for a in self.figure.get_axes():
self.figure.delaxes(a)
#self.axe111.clear()
#self.figure.draw()
self.figureCanvas.draw()
@pyqtSlot()
def snapshot(self, fileName = None):
if fileName is None:
caption = "%s - Save File" % self.name
filter = "PNG Image (*.png);;All files (*.*)"
fileName = QFileDialog.getSaveFileName(self.parent(), caption=caption,filter=filter )
fileName = "%s" % fileName
if len(fileName) > 0:
self.figure.savefig(fileName, facecolor='w', edgecolor='w', orientation='portrait', papertype=None, format=None, transparent=False, bbox_inches=None, pad_inches=0.1)
@pyqtSlot()
def addAxesSubplot(self, axesSubplot, position=None, bbox=None):
axesSubplot.set_figure(self.figure)
self.figure.add_axes(axesSubplot)
if position is not None:
axesSubplot.set_position(position)
if bbox is not None:
axesSubplot.set_position(bbox)
@pyqtSlot()
def addAxesSubplots(self, axesSubplots):
for axesSubplot in axesSubplots:
self.addSubplot(axesSubplot)
示例11: PlotPanel2DByTemperature
# 需要导入模块: from matplotlib.figure import Figure [as 别名]
# 或者: from matplotlib.figure.Figure import delaxes [as 别名]
class PlotPanel2DByTemperature(wx.Panel):
DEFAULT_MIN_TEMP = 0
DEFAULT_MAX_TEMP = 2000
NUM_TEMPS = 200
def __init__(self, parent, min_temp=None):
wx.Panel.__init__(self, parent)
self.min_temp = min_temp if min_temp is not None else self.DEFAULT_MIN_TEMP
self.max_temp = self.DEFAULT_MAX_TEMP
self.data_cache = None
# Panel.
panel_box = wx.BoxSizer(wx.VERTICAL)
## Canvas.
self.figure = Figure()
self.canvas = Canvas(self, -1, self.figure)
self.axes = None
panel_box.Add(self.canvas, 1, wx.EXPAND)
self.SetSizer(panel_box)
def plot_data(self, fs, bds, xlabel=None, ylabel=None):
self.data_cache = {
'fs': fs,
'bds': bds,
'xlabel': xlabel,
'ylabel': ylabel,
}
if self.axes is not None:
self.figure.delaxes(self.axes)
self.axes = None
self.axes = self.figure.add_subplot(111)
if xlabel is not None:
self.axes.set_xlabel(xlabel)
if ylabel is not None:
self.axes.set_ylabel(ylabel)
do_legend = False
for f, bd in zip(fs, bds):
label, color = bd.filename, bd.color
if not do_legend and label is not None:
do_legend = True
xs = self._gen_temps()
ys = [f(x) for x in xs]
self.axes.plot(xs, ys, label=label, color=color)
if do_legend:
# Put the legend in the top-right corner, outside the axes.
self.axes.legend(bbox_to_anchor=(0, 0, 1, 1), bbox_transform=self.figure.transFigure)
self.figure.tight_layout()
self.canvas.draw()
def plot_cached_data(self):
dc = self.data_cache
if dc is None:
return
self.plot_data(dc['fs'], dc['bds'], xlabel=dc['xlabel'], ylabel=dc['ylabel'])
def set_max_temp(self, temp):
self.max_temp = temp
self.plot_cached_data()
def _gen_temps(self):
return N.linspace(self.min_temp, self.max_temp, self.NUM_TEMPS)
示例12: PlotPanel3DPopulation
# 需要导入模块: from matplotlib.figure import Figure [as 别名]
# 或者: from matplotlib.figure.Figure import delaxes [as 别名]
class PlotPanel3DPopulation(wx.Panel):
def __init__(self, parent):
wx.Panel.__init__(self, parent)
# Panel.
panel_box = wx.BoxSizer(wx.VERTICAL)
## Canvas.
self.figure = Figure()
self.canvas = Canvas(self, -1, self.figure)
self.axes = None
panel_box.Add(self.canvas, 1, wx.EXPAND)
self.SetSizer(panel_box)
def plot_data(self, bd, cm=jet, xlabel=None, ylabel=None, zlabel=None):
"""
Plot energy level populations by temperature in 3D.
bd: BoltzmannDistribution.
cm: A matplotlib colormap.
*label: Axis labels.
"""
if self.axes is not None:
self.figure.delaxes(self.axes)
self.axes = None
self.axes = self.figure.gca(projection='3d')
# Set up the data.
xs = self._gen_temps()
ys = bd.energies
verts = []
# All the energy level populations at all the temperatures.
populations = N.column_stack(bd.ps(x) for x in xs)
for p in populations:
# Add the points on the ends so that there is a bottom edge along
# the polygon.
points = [(xs[0], 0)] + list(zip(xs, p)) + [(xs[-1], 0)]
verts.append(points)
x_min, x_max = min(xs), max(xs)
y_min, y_max = min(ys), max(ys)
if y_max == y_min:
colors = [cm(0.0) for i in bd.levels]
else:
colors = [cm((ys[i] - y_min) / (y_max - y_min)) for i in bd.levels]
poly = PolyCollection(verts, facecolors=colors, linewidth=1.0, edgecolor='white')
poly.set_alpha(0.7)
# The directions here look somewhat confused, but that's just due to
# the way the polygons are stacked.
self.axes.add_collection3d(poly, zs=ys, zdir='y')
if x_max == x_min:
self.axes.set_xlim3d(x_min - 1, x_max + 1)
else:
self.axes.set_xlim3d(x_min, x_max)
if y_max == y_min:
self.axes.set_ylim3d(y_min - 1, y_max + 1)
else:
self.axes.set_ylim3d(y_min, y_max)
self.axes.set_zlim3d(0, 1)
if xlabel is not None:
self.axes.set_xlabel(xlabel)
if ylabel is not None:
self.axes.set_ylabel(ylabel)
if zlabel is not None:
self.axes.set_zlabel(zlabel)
self.figure.tight_layout()
# Make sure that we redraw as the user drags.
#
# Using a list because we don't have nonlocal here.
mouse_down = [False]
def on_press(evt):
mouse_down[0] = True
def on_move(evt):
if mouse_down[0]:
self.canvas.draw()
def on_release(evt):
mouse_down[0] = False
cid = self.canvas.mpl_connect('button_press_event', on_press)
cid = self.canvas.mpl_connect('motion_notify_event', on_move)
cid = self.canvas.mpl_connect('button_release_event', on_release)
#.........这里部分代码省略.........
示例13: __init__
# 需要导入模块: from matplotlib.figure import Figure [as 别名]
# 或者: from matplotlib.figure.Figure import delaxes [as 别名]
#.........这里部分代码省略.........
self.f = Figure(figsize=(8,8), dpi=100)
self.a = self.f.add_subplot(111)
self.canvas = FigureCanvasTkAgg(self.f, master=root)
self.canvas.show()
self.canvas.get_tk_widget().pack(side=TOP, fill=BOTH, expand=1)
#self.toolbar = NavigationToolbar2TkAgg(self.canvas,frame)
#self.toolbar.update()
#self.canvas._tkcanvas.pack(side=TOP, fill=BOTH, expand=1)
def loaddata(self):
mynstep=int(self.enstep.get())
self.D = pp.pload(mynstep,w_dir=self.wdir)
return self.D
def getmyvar(self):
self.myvar=self.v.get()
def logchkcall(self):
self.logchk = self.logvar.get()
def polchkcall(self):
self.polchk = self.polarvar.get()
def setslice(self,event):
self.slicename=self.slvar.get()
def plotclear(self):
self.a.clear()
if len(self.f.axes)>1:
self.f.delaxes(self.f.axes[1])
self.f.subplots_adjust(right=0.90)
self.canvas.show()
def plotfinal(self):
if self.logvar.get() == 1:
self.var = log10(self.D.__getattribute__(self.myvar))
else:
self.var = self.D.__getattribute__(self.myvar)
if self.slicename == "Along x1":
self.x = self.D.x1
if self.grid_dict["n3"] == 1:
self.var = self.var[:,int(self.ex2.get())]
else:
self.var = self.var[:,int(self.ex2.get()),int(self.ex3.get())]
elif self.slicename == "Along x2":
self.x = self.D.x2
if self.grid_dict["n3"] == 1:
self.var = self.var[int(self.ex1.get()),:]
else:
self.var = self.var[int(self.ex1.get()),:,int(self.ex3.get())]
else:
self.x = self.D.x3
self.var = self.var[int(self.ex1.get()),int(self.ex2.get()),:]
self.a.set_aspect('auto')
self.a.plot(self.x,self.var)
self.a.set_xlabel(self.xlb.get())
self.a.set_ylabel(self.ylb.get())
示例14: Costmap2DFigure
# 需要导入模块: from matplotlib.figure import Figure [as 别名]
# 或者: from matplotlib.figure.Figure import delaxes [as 别名]
class Costmap2DFigure(FigureCanvas):
costmap_changed = QtCore.Signal()
"""Implements an imshow figure for showing the costmap2d"""
def __init__(self, costmap, parent=None, width=5.0, height=4.0, dpi=100, interpolation='nearest',
show_start = True, show_goal = True, show_colorbar = True):
self.lock = Lock()
self.costmap = costmap
self.freeze = False
self.interpolation = interpolation
self.fig = Figure(figsize=(width, height), dpi=dpi)
self.axes = self.fig.add_subplot(1,1,1)
# We want the axes cleared every time plot() is called
self.axes.hold(False)
self.show_start = show_start
self.start_coord = (-0.5, -0.5)
self.start = Rectangle(self.start_coord, 1, 1, color='g')
self.show_goal = show_goal
self.goal_coord = (self.costmap.width-1.5, self.costmap.height-1.5)
self.goal = Rectangle(self.goal_coord, 1, 1, color='k')
self.show_colorbar = show_colorbar
self.compute_initial_figure()
FigureCanvas.__init__(self, self.fig)
self.setParent(parent)
self.mpl_connect('button_release_event', self.on_mouse_release)
FigureCanvas.setSizePolicy(self,
QtGui.QSizePolicy.Expanding,
QtGui.QSizePolicy.Expanding)
FigureCanvas.updateGeometry(self)
self.on_mouse_click = self.default_on_mouse_click
# Idle control
self.idle = True
# Make Qt Connections
self.connect_stuff()
# Override costmap on change
self.costmap.on_update = self.costmap_update_callback
def on_mouse_release(self, e):
"""Gets called when a mouse button is released"""
if self.on_mouse_click != None:
self.on_mouse_click(e)
def default_on_mouse_click(self, e):
"""Default function for mouse clicking"""
if e.xdata == None or e.ydata == None:
return
from math import floor
coord = (floor(e.xdata+0.5)-0.5, floor(e.ydata+0.5)-0.5)
if -0.5 > coord[0] < self.costmap.width-1.5 or \
-0.5 > coord[1] < self.costmap.height-1.5:
return
if e.button == 1:
self.start_coord = coord
self.start = Rectangle(coord, 1, 1, color='g')
elif e.button == 3:
self.goal_coord = coord
self.goal = Rectangle(coord, 1, 1, color='k')
else:
return
self.on_map_update()
def connect_stuff(self):
"""Make Qt connections"""
self.costmap_changed.connect(self.on_map_update)
def costmap_update_callback(self, key, val):
"""Callback to handle when the map is updated"""
if self.idle:
self.idle = False
self.costmap_changed.emit()
def compute_initial_figure(self):
"""Plot the imshow"""
axes = self.axes.imshow(self.costmap.data.T, interpolation=self.interpolation)
if self.show_colorbar: self.colorbar = self.fig.colorbar(axes)
if self.show_start: self.axes.add_artist(self.start)
if self.show_goal: self.axes.add_artist(self.goal)
def on_map_update(self):
"""Slot to handle the costmap_changed signal"""
if self.freeze: return
self.lock.acquire()
axes = self.axes.imshow(self.costmap.data.T, interpolation=self.interpolation)
if self.show_colorbar:
self.fig.delaxes(self.fig.axes[1])
self.fig.subplots_adjust(right=0.90)
self.colorbar = self.fig.colorbar(axes)
if self.show_start: self.axes.add_artist(self.start)
if self.show_goal: self.axes.add_artist(self.goal)
self.draw()
#.........这里部分代码省略.........
示例15: plothistogram
# 需要导入模块: from matplotlib.figure import Figure [as 别名]
# 或者: from matplotlib.figure.Figure import delaxes [as 别名]
#.........这里部分代码省略.........
self.histogramBinSpin=QSpinBox() # spinbox for histogram binsize
self.histogramBinSpin.setToolTip("Number of bins to histogram into")
self.histogramBinSpin.setMinimum(5)
#self.histogramBinSpin.setMaximum(150) # set a maximum of 150 (reasonable?)
self.histogramBinSpin.setSingleStep(10) # allow only stepping by 10
self.histogramBinSpin.setMaximumWidth(120)
self.histogramBinSpin.setMinimumHeight(25)
self.histogramBinSpin.setValue(self.nbins)
self.histogramBinSpin.show()
self.histogramBinLabel=QLabel("Bins")
self.normedCheckBox=QCheckBox()
self.normedCheckLabel=QLabel("Normalize")
self.normedCheckBox.setToolTip("Normalize histogram")
self.normedCheckBox.show()
#self.dpi = 100
self.dataComboBox=QComboBox()
self.dataComboBox.addItem(self.parent.parent.parmValueComboBox.currentText())
self.dataComboBox.addItem(self.parent.parent.parametersComboBox.currentText())
self.dataComboBox.setMaximumWidth(120)
self.dataComboBox.setMinimumHeight(25)
self.dataComboBox.setCurrentIndex(1)
def createLayout(self):
#print "createLayout()" # DEBUG
self.normedLayout=QHBoxLayout()
self.normedLayout.addWidget(self.normedCheckBox)
self.normedLayout.addWidget(self.normedCheckLabel)
self.buttonLayout=QVBoxLayout()
self.plotLayout=QVBoxLayout()
self.mainLayout=QHBoxLayout()
self.buttonLayout.addLayout(self.normedLayout)
#self.buttonLayout.addWidget(self.normedCheckBox)
#self.buttonLayout.addWidget(self.normedCheckLabel)
self.buttonLayout.addWidget(self.histogramBinSpin)
self.buttonLayout.addWidget(self.dataComboBox)
self.buttonLayout.insertStretch(-1)
self.buttonLayout.addWidget(self.closeButton)
self.plotLayout.addWidget(self.canvas)
self.plotLayout.addWidget(self.mpl_toolbar)
self.mainLayout.addLayout(self.buttonLayout)
self.mainLayout.addLayout(self.plotLayout)
self.setLayout(self.mainLayout)
def setLabels(self):
self.ax.xlabel="Bin"
self.ax.ylabel="N"
def setTitle(self):
#=self.parent.parametersComboBox.currentText()
#self.ax.xlabel=self.parmValueComboBox.currentText()
#self.ax.xlabel="Bin No."
#self.ax.ylabel="n"
self.ax.title=self.parent.parent.parametersComboBox.currentText()
def connectSignals(self):
self.connect(self.closeButton, SIGNAL('clicked()'), SLOT('close()'))
self.connect(self.histogramBinSpin, SIGNAL('valueChanged(int)'), self.on_changeBinSpin)
self.connect(self.normedCheckBox, SIGNAL('stateChanged(int)'), self.on_normedCheckBox)
self.connect(self.dataComboBox, SIGNAL('currentIndexChanged(int)'), self.on_data)
def on_changeBinSpin(self):
self.nbins=self.histogramBinSpin.value()
# create histogram
#n, bins = np.histogram(self.data, self.histogramBinSpin.value(), normed=self.normedCheckBox.isChecked())
#hist, bins=np.histogram(self.data, self.nbins, normed=self.normedCheckBox.isChecked())
#print "len(bins) = ", len(bins), " len(n) = ", len(n)
#self.ax.plot(bins[1:], n, color='red')
#self.canvas.draw()
#self.ax.legend()
#self.fig.draw_idle() # redraw (preferably when idle)
self.plot()
def on_normedCheckBox(self):
self.plot()
def on_data(self):
print "on_data()" # DEBUG
if self.dataComboBox.currentText()==self.parent.parent.parametersComboBox.currentText():
self.data=self.data2
else:
self.data=self.data1
self.plot()
def plot(self):
self.fig.delaxes(self.ax) # delete all axes first
self.ax=self.fig.add_subplot(111)
n, bins = np.histogram(self.data, self.histogramBinSpin.value(), normed=self.normedCheckBox.isChecked())
self.xmin=bins[1]
self.xmax=bins[len(bins)-1]
self.ax.bar(bins[1:], n, color='blue', width=(self.xmax-self.xmin)/len(bins))
self.canvas.draw()