def __init__(self, t, u, show_plot=False):
SimulationInput.__init__(self)
self._t = t
self._T = t[-1]
self._u = u
self.scale = 1
if show_plot:
pw = pg.plot(title="InterpTrajectory")
pw.plot(self._t, self.__call__(time=self._t))
pw.plot([0, self._T], self.__call__(time=[0, self._T]), pen=None, symbolPen=pg.mkPen("g"))
pg.QtGui.QApplication.instance().exec_()
python类plot()的实例源码
def __init__(self, data, title="", dt=None):
PgDataPlot.__init__(self, data)
self.time_data = [np.atleast_1d(data_set.input_data[0]) for data_set in self._data]
self.spatial_data = [np.atleast_1d(data_set.input_data[1]) for data_set in self._data]
self.state_data = [data_set.output_data for data_set in self._data]
self._pw = pg.plot(title=time.strftime("%H:%M:%S") + ' - ' + title)
self._pw.addLegend()
self._pw.showGrid(x=True, y=True, alpha=0.5)
max_times = [max(data) for data in self.time_data]
self._endtime = max(max_times)
self._longest_idx = max_times.index(self._endtime)
if dt is not None:
self._dt = dt
spat_min = np.min([np.min(data) for data in self.spatial_data])
spat_max = np.max([np.max(data) for data in self.spatial_data])
self._pw.setXRange(spat_min, spat_max)
state_min = np.min([np.min(data) for data in self.state_data])
state_max = np.max([np.max(data) for data in self.state_data])
self._pw.setYRange(state_min, state_max)
self._time_text = pg.TextItem('t= 0')
self._pw.addItem(self._time_text)
self._time_text.setPos(.9 * spat_max, .9 * state_min)
self._plot_data_items = []
for idx, data_set in enumerate(self._data):
self._plot_data_items.append(pg.PlotDataItem(pen=colors[idx], name=data_set.name))
self._pw.addItem(self._plot_data_items[-1])
self._curr_frame = 0
self._t = 0
self._timer = pg.QtCore.QTimer()
self._timer.timeout.connect(self._update_plot)
self._timer.start(1e3 * self._dt)
def __init__(self, data, title=None):
PgDataPlot.__init__(self, data)
self.dim = self._data[0].output_data.shape
self.win = pg.QtGui.QMainWindow()
self.win.resize(800, 800)
self.win.setWindowTitle("PgSlicePlot: {}".format(title))
self.cw = pg.QtGui.QWidget()
self.win.setCentralWidget(self.cw)
self.l = pg.QtGui.QGridLayout()
self.cw.setLayout(self.l)
self.image_view = pg.ImageView(name="img_view")
self.l.addWidget(self.image_view, 0, 0)
self.slice_view = pg.PlotWidget(name="slice")
self.l.addWidget(self.slice_view)
self.win.show()
# self.imv2 = pg.ImageView()
# self.l.addWidget(self.imv2, 1, 0)
self.roi = pg.LineSegmentROI([[0, self.dim[1] - 1], [self.dim[0] - 1, self.dim[1] - 1]], pen='r')
self.image_view.addItem(self.roi)
self.image_view.setImage(self._data[0].output_data)
#
# self.plot_window.showGrid(x=True, y=True, alpha=.5)
# self.plot_window.addLegend()
#
# input_idx = 0 if self.data_slice.shape[0] > self.data_slice.shape[1] else 0
# for data_set in data:
# self.plot_window.plot(data_set.input_data[input_idx], data_set.output_data[self.data_slice],
# name=data.name)
# TODO: alpha
oscilloscope_plotting_pyqtgraph.py 文件源码
项目:pymoku
作者: liquidinstruments
项目源码
文件源码
阅读 15
收藏 0
点赞 0
评论 0
def update():
global line1, line2
data = i.get_realtime_data()
# Update the plot
line1.setData(data.time, data.ch1)
line2.setData(data.time, data.ch2)
def test_mouseInteraction():
plt = pg.plot()
plt.scene().minDragTime = 0 # let us simulate mouse drags very quickly.
vline = plt.addLine(x=0, movable=True)
plt.addItem(vline)
hline = plt.addLine(y=0, movable=True)
hline2 = plt.addLine(y=-1, movable=False)
plt.setXRange(-10, 10)
plt.setYRange(-10, 10)
# test horizontal drag
pos = plt.plotItem.vb.mapViewToScene(pg.Point(0,5)).toPoint()
pos2 = pos - QtCore.QPoint(200, 200)
mouseMove(plt, pos)
assert vline.mouseHovering is True and hline.mouseHovering is False
mouseDrag(plt, pos, pos2, QtCore.Qt.LeftButton)
px = vline.pixelLength(pg.Point(1, 0), ortho=True)
assert abs(vline.value() - plt.plotItem.vb.mapSceneToView(pos2).x()) <= px
# test missed drag
pos = plt.plotItem.vb.mapViewToScene(pg.Point(5,0)).toPoint()
pos = pos + QtCore.QPoint(0, 6)
pos2 = pos + QtCore.QPoint(-20, -20)
mouseMove(plt, pos)
assert vline.mouseHovering is False and hline.mouseHovering is False
mouseDrag(plt, pos, pos2, QtCore.Qt.LeftButton)
assert hline.value() == 0
# test vertical drag
pos = plt.plotItem.vb.mapViewToScene(pg.Point(5,0)).toPoint()
pos2 = pos - QtCore.QPoint(50, 50)
mouseMove(plt, pos)
assert vline.mouseHovering is False and hline.mouseHovering is True
mouseDrag(plt, pos, pos2, QtCore.Qt.LeftButton)
px = hline.pixelLength(pg.Point(1, 0), ortho=True)
assert abs(hline.value() - plt.plotItem.vb.mapSceneToView(pos2).y()) <= px
# test non-interactive line
pos = plt.plotItem.vb.mapViewToScene(pg.Point(5,-1)).toPoint()
pos2 = pos - QtCore.QPoint(50, 50)
mouseMove(plt, pos)
assert hline2.mouseHovering == False
mouseDrag(plt, pos, pos2, QtCore.Qt.LeftButton)
assert hline2.value() == -1
def test_mouseInteraction():
plt = pg.plot()
plt.scene().minDragTime = 0 # let us simulate mouse drags very quickly.
vline = plt.addLine(x=0, movable=True)
plt.addItem(vline)
hline = plt.addLine(y=0, movable=True)
hline2 = plt.addLine(y=-1, movable=False)
plt.setXRange(-10, 10)
plt.setYRange(-10, 10)
# test horizontal drag
pos = plt.plotItem.vb.mapViewToScene(pg.Point(0,5)).toPoint()
pos2 = pos - QtCore.QPoint(200, 200)
mouseMove(plt, pos)
assert vline.mouseHovering is True and hline.mouseHovering is False
mouseDrag(plt, pos, pos2, QtCore.Qt.LeftButton)
px = vline.pixelLength(pg.Point(1, 0), ortho=True)
assert abs(vline.value() - plt.plotItem.vb.mapSceneToView(pos2).x()) <= px
# test missed drag
pos = plt.plotItem.vb.mapViewToScene(pg.Point(5,0)).toPoint()
pos = pos + QtCore.QPoint(0, 6)
pos2 = pos + QtCore.QPoint(-20, -20)
mouseMove(plt, pos)
assert vline.mouseHovering is False and hline.mouseHovering is False
mouseDrag(plt, pos, pos2, QtCore.Qt.LeftButton)
assert hline.value() == 0
# test vertical drag
pos = plt.plotItem.vb.mapViewToScene(pg.Point(5,0)).toPoint()
pos2 = pos - QtCore.QPoint(50, 50)
mouseMove(plt, pos)
assert vline.mouseHovering is False and hline.mouseHovering is True
mouseDrag(plt, pos, pos2, QtCore.Qt.LeftButton)
px = hline.pixelLength(pg.Point(1, 0), ortho=True)
assert abs(hline.value() - plt.plotItem.vb.mapSceneToView(pos2).y()) <= px
# test non-interactive line
pos = plt.plotItem.vb.mapViewToScene(pg.Point(5,-1)).toPoint()
pos2 = pos - QtCore.QPoint(50, 50)
mouseMove(plt, pos)
assert hline2.mouseHovering == False
mouseDrag(plt, pos, pos2, QtCore.Qt.LeftButton)
assert hline2.value() == -1
def plot_trace(xy, ids = None, depth = 0, colormap = 'rainbow', line_color = 'k', line_width = 1, point_size = 5, title = None):
"""Plot trajectories with positions color coded according to discrete ids"""
#if ids is not None:
uids = np.unique(ids);
cmap = cm.get_cmap(colormap);
n = len(uids);
colors = cmap(range(n), bytes = True);
#lines
if line_width is not None:
#plt.plot(xy[:,0], xy[:,1], color = lines);
plot = pg.plot(xy[:,0], xy[:,1], pen = pg.mkPen(color = line_color, width = line_width))
else:
plot = pg.plot(title = title);
if ids is None:
sp = pg.ScatterPlotItem(pos = xy, size=point_size, pen=pg.mkPen(colors[0])); #, pxMode=True);
else:
sp = pg.ScatterPlotItem(size=point_size); #, pxMode=True);
spots = [];
for j,i in enumerate(uids):
idx = ids == i;
spots.append({'pos': xy[idx,:].T, 'data': 1, 'brush':pg.mkBrush(colors[j])}); #, 'size': point_size});
sp.addPoints(spots)
plot.addItem(sp);
return plot;
# legs = [];
# for k,i in enumerate(uids):
# ii = np.where(ids == i)[0];
# if depth > 0:
# ii = [ii-d for d in range(depth)];
# ii = np.unique(np.concatenate(ii));
#
# plt.plot(data[ii, 0], data[ii, 1], '.', color = color[k]);
#
# legs.append(mpatches.Patch(color=color[k], label= str(i)));
#
# plt.legend(handles=legs);
def plot_trace(xy, ids = None, depth = 0, colormap = 'rainbow', line_color = 'k', line_width = 1, point_size = 5, title = None):
"""Plot trajectories with positions color coded according to discrete ids"""
#if ids is not None:
uids = np.unique(ids);
cmap = cm.get_cmap(colormap);
n = len(uids);
colors = cmap(range(n), bytes = True);
#lines
if line_width is not None:
#plt.plot(xy[:,0], xy[:,1], color = lines);
plot = pg.plot(xy[:,0], xy[:,1], pen = pg.mkPen(color = line_color, width = line_width))
else:
plot = pg.plot(title = title);
if ids is None:
sp = pg.ScatterPlotItem(pos = xy, size=point_size, pen=pg.mkPen(colors[0])); #, pxMode=True);
else:
sp = pg.ScatterPlotItem(size=point_size); #, pxMode=True);
spots = [];
for j,i in enumerate(uids):
idx = ids == i;
spots.append({'pos': xy[idx,:].T, 'data': 1, 'brush':pg.mkBrush(colors[j])}); #, 'size': point_size});
sp.addPoints(spots)
plot.addItem(sp);
return plot;
# legs = [];
# for k,i in enumerate(uids):
# ii = np.where(ids == i)[0];
# if depth > 0:
# ii = [ii-d for d in range(depth)];
# ii = np.unique(np.concatenate(ii));
#
# plt.plot(data[ii, 0], data[ii, 1], '.', color = color[k]);
#
# legs.append(mpatches.Patch(color=color[k], label= str(i)));
#
# plt.legend(handles=legs);
def plot_embedding_contours(Y, contours = 10, cmap = 'plasma', xmin = None, xmax = None, ymin = None, ymax = None, npts = 100, density = False):
"""Plot a 2d density map of the embedding Y"""
if xmin is None:
xmin = np.min(Y[:,0]);
if xmax is None:
xmax = np.max(Y[:,0]);
if ymin is None:
ymin = np.min(Y[:,1]);
if ymax is None:
ymax = np.max(Y[:,1]);
#print xmin,xmax,ymin,ymax
dx = float(xmax-xmin) / npts;
dy = float(ymax-ymin) / npts;
xx, yy = np.mgrid[xmin:xmax:dx, ymin:ymax:dy]
positions = np.vstack([xx.ravel(), yy.ravel()])
kernel = st.gaussian_kde(Y.T);
#print xx.shape
#print positions.shape
#print Y.shape
#print kernel(positions).shape
f = kernel(positions)
f = np.reshape(f, xx.shape)
#print f.shape
ax = plt.gca()
ax.set_xlim(xmin, xmax)
ax.set_ylim(ymin, ymax)
# Contourf plot
if density:
cfset = ax.contourf(xx, yy, f, cmap=cmap)
## Or kernel density estimate plot instead of the contourf plot
#ax.imshow(np.rot90(f), cmap='Blues', extent=[xmin, xmax, ymin, ymax])
# Contour plot
if contours is not None:
cset = ax.contour(xx, yy, f, contours, cmap=cmap)
# Label plot
#ax.clabel(cset, inline=1, fontsize=10)
ax.set_xlabel('Y0')
ax.set_ylabel('Y1')
return (kernel, f)
def shape_generator(self, cls, der_order):
"""
verify the correct connection with visual feedback
"""
dz = pi.Domain((0, 1), step=.001)
dt = pi.Domain((0, 0), num=1)
nodes, funcs = pi.cure_interval(cls, dz.bounds, node_count=11)
pi.register_base("test", funcs, overwrite=True)
# approx_func = pi.Function(np.cos, domain=dz.bounds,
# derivative_handles=[lambda z: -np.sin(z), lambda z: -np.cos(z)])
approx_func = pi.Function(lambda z: np.sin(3*z), domain=dz.bounds,
derivative_handles=[lambda z: 3*np.cos(3*z), lambda z: -9*np.sin(3*z)])
weights = approx_func(nodes)
hull = pi.evaluate_approximation("test", np.atleast_2d(weights),
temp_domain=dt, spat_domain=dz, spat_order=der_order)
if show_plots:
# plot shapefunctions
c_map = pi.visualization.create_colormap(len(funcs))
pw = pg.plot(title="{}-Test".format(cls.__name__))
pw.addLegend()
pw.showGrid(x=True, y=True, alpha=0.5)
[pw.addItem(pg.PlotDataItem(np.array(dz),
weights[idx]*func.derive(der_order)(dz),
pen=pg.mkPen(color=c_map[idx]),
name="{}.{}".format(cls.__name__, idx)))
for idx, func in enumerate(funcs)]
# plot hull curve
pw.addItem(pg.PlotDataItem(np.array(hull.input_data[1]), hull.output_data[0, :],
pen=pg.mkPen(width=2), name="hull-curve"))
# plot original function
pw.addItem(pg.PlotDataItem(np.array(dz), approx_func.derive(der_order)(dz),
pen=pg.mkPen(color="m", width=2, style=pg.QtCore.Qt.DashLine), name="original"))
pg.QtCore.QCoreApplication.instance().exec_()
return np.sum(np.abs(hull.output_data[0, :] - approx_func.derive(der_order)(dz)))