def updatePlot(self):
# Lists for positions of cars
x=[]
y=[]
color = []
carSymbol = []
for car in Plotter.instance()._trafficManager.cars:
x.append(car.getPosition())
y.append((car.getLane() * self._laneWidth) - (self._laneWidth/2.))
color.append(pg.mkBrush(car.getColor()))
if (car.getType() == 'b'):
carSymbol.append('d')
elif (car.getType() == 's'):
carSymbol.append('o')
elif (car.getType() == 'a'):
carSymbol.append('+')
else:
carSymbol.append('t')
self._pw.plot(x, y, clear=True, pen=None, symbol=carSymbol, symbolSize=20, symbolBrush = color)
self._pw.addItem(self._backgroundImage)
self._backgroundImage.setZValue(-100) # make sure image is behind other data
self._backgroundImage.setRect(pg.QtCore.QRectF(0, 0, self._roadLength, self._roadWidth))
pg.QtGui.QApplication.processEvents()
python类mkBrush()的实例源码
def __init__(self, plot, parent=None):
QtGui.QDialog.__init__(self, parent)
loadUi(get_resource('transect.ui'), baseinstance=self)
pxmap = self.style().standardPixmap
self.closeButton.setIcon(
pxmap(QtGui.QStyle.SP_DialogCloseButton))
self.createButton.setIcon(
pxmap(QtGui.QStyle.SP_ArrowUp))
self.removeButton.setIcon(
pxmap(QtGui.QStyle.SP_DialogDiscardButton))
self.plot = plot
self.poly_line = None
self.trans_plot = pg.PlotDataItem(
antialias=True,
fillLevel=0.,
fillBrush=pg.mkBrush(0, 127, 0, 150))
self.plt_wdgt = pg.PlotWidget()
self.plt_wdgt.setLabels(
bottom={'Distance', 'm'},
left='Displacement [m]')
self.plt_wdgt.showGrid(True, True, alpha=.5)
self.plt_wdgt.enableAutoRange()
self.plt_wdgt.addItem(self.trans_plot)
self.layoutPlot.addWidget(self.plt_wdgt)
self.plot.image.sigImageChanged.connect(self.updateTransPlot)
self.createButton.released.connect(self.addPolyLine)
self.removeButton.released.connect(self.removePolyLine)
parent.model.sigConfigChanged.connect(self.close)
def __init__(self, parent=None):
pyqtgraph.setConfigOption('background', 'w') #before loading widget
super(ExampleApp, self).__init__(parent)
self.setupUi(self)
self.grECG.plotItem.showGrid(True, True, 0.7)
self.btnSave.clicked.connect(self.saveFig)
self.btnSite.clicked.connect(self.website)
stamp="DIY ECG by Scott Harden"
self.stamp = pyqtgraph.TextItem(stamp,anchor=(-.01,1),color=(150,150,150),
fill=pyqtgraph.mkBrush('w'))
self.ear = swhear.Ear(chunk=int(100)) # determines refresh rate
# optionally you can manually set the audio input device to use like this:
# self.ear = swhear.Ear(chunk=int(100), device=5) # use audio input device 5
if len(self.ear.valid_input_devices()):
self.ear.stream_start()
self.lblDevice.setText(self.ear.msg)
self.update()
def test_init_spots():
plot = pg.PlotWidget()
# set view range equal to its bounding rect.
# This causes plots to look the same regardless of pxMode.
plot.setRange(rect=plot.boundingRect())
spots = [
{'x': 0, 'y': 1},
{'pos': (1, 2), 'pen': None, 'brush': None, 'data': 'zzz'},
]
s = pg.ScatterPlotItem(spots=spots)
# Check we can display without errors
plot.addItem(s)
app.processEvents()
plot.clear()
# check data is correct
spots = s.points()
defPen = pg.mkPen(pg.getConfigOption('foreground'))
assert spots[0].pos().x() == 0
assert spots[0].pos().y() == 1
assert spots[0].pen() == defPen
assert spots[0].data() is None
assert spots[1].pos().x() == 1
assert spots[1].pos().y() == 2
assert spots[1].pen() == pg.mkPen(None)
assert spots[1].brush() == pg.mkBrush(None)
assert spots[1].data() == 'zzz'
def test_init_spots():
plot = pg.PlotWidget()
# set view range equal to its bounding rect.
# This causes plots to look the same regardless of pxMode.
plot.setRange(rect=plot.boundingRect())
spots = [
{'x': 0, 'y': 1},
{'pos': (1, 2), 'pen': None, 'brush': None, 'data': 'zzz'},
]
s = pg.ScatterPlotItem(spots=spots)
# Check we can display without errors
plot.addItem(s)
app.processEvents()
plot.clear()
# check data is correct
spots = s.points()
defPen = pg.mkPen(pg.getConfigOption('foreground'))
assert spots[0].pos().x() == 0
assert spots[0].pos().y() == 1
assert spots[0].pen() == defPen
assert spots[0].data() is None
assert spots[1].pos().x() == 1
assert spots[1].pos().y() == 2
assert spots[1].pen() == pg.mkPen(None)
assert spots[1].brush() == pg.mkBrush(None)
assert spots[1].data() == 'zzz'
def generatePicture(self):
## pre-computing a QPicture object allows paint() to run much more quickly,
## rather than re-drawing the shapes every time.
self.picture = QtGui.QPicture()
p = QtGui.QPainter(self.picture)
p.setPen(pg.mkPen(color='r', width=0.4)) # 0.4 means w*2
# w = (self.data[1][0] - self.data[0][0]) / 3.
w = 0.2
for (t, open, close, min, max) in self.data:
p.drawLine(QtCore.QPointF(t, min), QtCore.QPointF(t, max))
if open > close:
p.setBrush(pg.mkBrush('g'))
else:
p.setBrush(pg.mkBrush('r'))
p.drawRect(QtCore.QRectF(t-w, open, w*2, close-open))
p.end()
def generatePicture(self):
## pre-computing a QPicture object allows paint() to run much more quickly,
## rather than re-drawing the shapes every time.
self.picture = QtGui.QPicture()
p = QtGui.QPainter(self.picture)
p.setPen(pg.mkPen(color='r', width=0.4)) # 0.4 means w*2
# w = (self.data[1][0] - self.data[0][0]) / 3.
w = 0.2
for (t, open, close, min, max) in self.data:
p.drawLine(QtCore.QPointF(t, min), QtCore.QPointF(t, max))
if open > close:
p.setBrush(pg.mkBrush('g'))
else:
p.setBrush(pg.mkBrush('r'))
p.drawRect(QtCore.QRectF(t-w, open, w*2, close-open))
p.end()
def plot_scatter_points(self, x_data, y_data):
if self.scatterplot_item:
self.plotview.removeItem(self.scatterplot_item)
self.n_points = len(x_data)
self.scatterplot_item = pg.ScatterPlotItem(
x=x_data, y=y_data, data=np.arange(self.n_points),
symbol="o", size=10, pen=pg.mkPen(0.2), brush=pg.mkBrush(0.7),
antialias=True)
self.scatterplot_item.opts["useCache"] = False
self.plotview.addItem(self.scatterplot_item)
self.plotview.replot()
def __init__(self, *args, **kwargs):
pg.LinearRegionItem.__init__(self, *args, **kwargs)
for l in self.lines:
l.setCursor(Qt.SizeHorCursor)
self.setZValue(10)
color = QColor(Qt.red)
color.setAlphaF(0.05)
self.setBrush(pg.mkBrush(color))
def add_fill_curve(self, x, ylow, yhigh, pen):
phigh = pg.PlotCurveItem(x, yhigh, pen=pen)
plow = pg.PlotCurveItem(x, ylow, pen=pen)
color = pen.color()
color.setAlphaF(0.2)
cc = pg.mkBrush(color)
pfill = pg.FillBetweenItem(plow, phigh, brush=cc)
pfill.setZValue(10)
self.curves_cont.add_bounds(phigh)
self.curves_cont.add_bounds(plow)
self.curves_cont.add_curve(pfill, ignore_bounds=True)
# for zoom to work correctly
self.curves_plotted.append((x, np.array([ylow, yhigh])))
def test_scatterplotitem():
plot = pg.PlotWidget()
# set view range equal to its bounding rect.
# This causes plots to look the same regardless of pxMode.
plot.setRange(rect=plot.boundingRect())
for i, pxMode in enumerate([True, False]):
for j, useCache in enumerate([True, False]):
s = pg.ScatterPlotItem()
s.opts['useCache'] = useCache
plot.addItem(s)
s.setData(x=np.array([10,40,20,30])+i*100, y=np.array([40,60,10,30])+j*100, pxMode=pxMode)
s.addPoints(x=np.array([60, 70])+i*100, y=np.array([60, 70])+j*100, size=[20, 30])
# Test uniform spot updates
s.setSize(10)
s.setBrush('r')
s.setPen('g')
s.setSymbol('+')
app.processEvents()
# Test list spot updates
s.setSize([10] * 6)
s.setBrush([pg.mkBrush('r')] * 6)
s.setPen([pg.mkPen('g')] * 6)
s.setSymbol(['+'] * 6)
s.setPointData([s] * 6)
app.processEvents()
# Test array spot updates
s.setSize(np.array([10] * 6))
s.setBrush(np.array([pg.mkBrush('r')] * 6))
s.setPen(np.array([pg.mkPen('g')] * 6))
s.setSymbol(np.array(['+'] * 6))
s.setPointData(np.array([s] * 6))
app.processEvents()
# Test per-spot updates
spot = s.points()[0]
spot.setSize(20)
spot.setBrush('b')
spot.setPen('g')
spot.setSymbol('o')
spot.setData(None)
app.processEvents()
plot.clear()
def test_scatterplotitem():
plot = pg.PlotWidget()
# set view range equal to its bounding rect.
# This causes plots to look the same regardless of pxMode.
plot.setRange(rect=plot.boundingRect())
for i, pxMode in enumerate([True, False]):
for j, useCache in enumerate([True, False]):
s = pg.ScatterPlotItem()
s.opts['useCache'] = useCache
plot.addItem(s)
s.setData(x=np.array([10,40,20,30])+i*100, y=np.array([40,60,10,30])+j*100, pxMode=pxMode)
s.addPoints(x=np.array([60, 70])+i*100, y=np.array([60, 70])+j*100, size=[20, 30])
# Test uniform spot updates
s.setSize(10)
s.setBrush('r')
s.setPen('g')
s.setSymbol('+')
app.processEvents()
# Test list spot updates
s.setSize([10] * 6)
s.setBrush([pg.mkBrush('r')] * 6)
s.setPen([pg.mkPen('g')] * 6)
s.setSymbol(['+'] * 6)
s.setPointData([s] * 6)
app.processEvents()
# Test array spot updates
s.setSize(np.array([10] * 6))
s.setBrush(np.array([pg.mkBrush('r')] * 6))
s.setPen(np.array([pg.mkPen('g')] * 6))
s.setSymbol(np.array(['+'] * 6))
s.setPointData(np.array([s] * 6))
app.processEvents()
# Test per-spot updates
spot = s.points()[0]
spot.setSize(20)
spot.setBrush('b')
spot.setPen('g')
spot.setSymbol('o')
spot.setData(None)
app.processEvents()
plot.clear()
def update_plot(self):
# first, we compile the line plot data, then we iterate over them and
# plot them. we then plot the scatter plots in the same manner
tfargs = {} # args to the call of iir.transfer_function
frequencies = self.frequencies
plot = OrderedDict()
# plot underlying curve data
try:
plot['data'] = self.module._data_curve_object.data.values
except AttributeError: # no curve for plotting available
plot['data'] = []
# plot designed filter
plot['filter_design'] = self.module.transfer_function(frequencies,
**tfargs)
# plot product
try:
plot['data_x_design'] = plot['data'] / plot['filter_design']
except ValueError:
try:
plot['data_x_design'] = 1.0 / plot['filter_design']
except:
plot['data_x_design'] = []
# plot everything (all lines) up to here
for k, v in plot.items():
self.graph_widget.plots[k].setData(frequencies[:len(v)],
self._magnitude(v))
self.graph_widget.plots[k+'_phase'].setData(frequencies[:len(v)],
self._phase(v))
# plot poles and zeros
aws = self.attribute_widgets
for end in ['poles', 'zeros']:
mag, phase = [], []
for start in ['complex', 'real']:
key = start+'_'+end
freq = getattr(self.module, key)
if start == 'complex':
freq = np.imag(freq)
freq = np.abs(freq)
tf = self.module.transfer_function(freq, **tfargs)
selected = aws[key].attribute_value.selected
brush = [pg.mkBrush(color='b')
if (num == selected)
else pg.mkBrush(color='y')
for num in range(aws[key].number)]
mag += [{'pos': (fr, val), 'data': i, 'brush': br}
for (i, (fr, val, br))
in enumerate(zip(list(np.log10(freq)),
list(self._magnitude(tf)),
brush))]
phase += [{'pos': (fr, val), 'data': i, 'brush': br}
for (i, (fr, val, br))
in enumerate(zip(list(np.log10(freq)),
list(self._phase(tf)),
brush))]
self.graph_widget.plots[end].setPoints(mag)
self.graph_widget.plots[end+'_phase'].setPoints(phase)
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 refresh_integral_markings(dis, markings_list, curveplot):
for m in markings_list:
if m in curveplot.markings:
curveplot.remove_marking(m)
markings_list.clear()
def add_marking(a):
markings_list.append(a)
curveplot.add_marking(a)
for di in dis:
if di is None:
continue # nothing to draw
color = QColor(di.get("color", "red"))
for el in di["draw"]:
if el[0] == "curve":
bs_x, bs_ys, penargs = el[1]
curve = pg.PlotCurveItem()
curve.setPen(pg.mkPen(color=QColor(color), **penargs))
curve.setZValue(10)
curve.setData(x=bs_x, y=bs_ys[0])
add_marking(curve)
elif el[0] == "fill":
(x1, ys1), (x2, ys2) = el[1]
phigh = pg.PlotCurveItem(x1, ys1[0], pen=None)
plow = pg.PlotCurveItem(x2, ys2[0], pen=None)
color = QColor(color)
color.setAlphaF(0.5)
cc = pg.mkBrush(color)
pfill = pg.FillBetweenItem(plow, phigh, brush=cc)
pfill.setZValue(9)
add_marking(pfill)
elif el[0] == "line":
(x1, y1), (x2, y2) = el[1]
line = pg.PlotCurveItem()
line.setPen(pg.mkPen(color=QColor(color), width=4))
line.setZValue(10)
line.setData(x=[x1[0], x2[0]], y=[y1[0], y2[0]])
add_marking(line)
elif el[0] == "dot":
(x, ys) = el[1]
dot = pg.ScatterPlotItem(x=x, y=ys[0])
dot.setPen(pg.mkPen(color=QColor(color), width=5))
dot.setZValue(10)
add_marking(dot)