写在前面:
pyqtgraph包中现有的例子中,蜡烛图的缩放不是很好用。这里做了一些修改,使用起来更自然些。
放置蜡烛图控件的父容器设置
v.setMouseEnabled(x=True, y=False)
v.setAutoVisible(x=False, y=True)文章来源:https://www.toymoban.com/news/detail-790184.html
修改后的蜡烛图控件
class CandlestickItem(pg.GraphicsObject):
def __init__(self, data):
pg.GraphicsObject.__init__(self)
self.data = data ## data must have fields: time, open, close, min, max
self.generatePicture()
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('d'))
w = (self.data[1][0] - self.data[0][0]) / 3.
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('r'))
else:
p.setBrush(pg.mkBrush('g'))
p.drawRect(QtCore.QRectF(t-w, open, w * 2, close - open))
p.end()
def paint(self, p, *args):
p.drawPicture(0, 0, self.picture)
def boundingRect(self):
## boundingRect _must_ indicate the entire area that will be drawn on
## or else we will get artifacts and possibly crashing.
## (in this case, QPicture does all the work of computing the bouning rect for us)
return QtCore.QRectF(self.picture.boundingRect())
# data = np.array(self.data)
# xmin = data[:, 0].min()
# xmax = data[:, 0].max()
# ymin = data[:, 1:].min()
# ymax = data[:, 1:].max()
# return QtCore.QRectF(xmin, ymin, xmax - xmin, ymax - ymin)
def viewTransformChanged(self):
super(CandlestickItem, self).viewTransformChanged()
br = self.boundingRect()
data = np.array(self.data)
# Get coords of view mapped to data
mapped_view = self.mapRectToView(self.viewRect())
# Get start and end of x slice
x_slice_start = int(mapped_view.x()) - 1
x_slice_end = x_slice_start + (math.ceil(mapped_view.width()) + 1)
if x_slice_start < 0:
x_slice_start = 0
if x_slice_end > data.shape[0]:
x_slice_end = data.shape[0]
# Get data in x interval
y_slice = data[x_slice_start:x_slice_end]
try:
ymin = np.nanmin(y_slice[:, 2])
ymax = np.nanmax(y_slice[:, 2])
if ymin != ymax:
if type(self.getViewBox())!= pg.ViewBox:
pass
else:
self.getViewBox().setLimits(xMin=br.x(), xMax=br.width(), yMin=ymin, yMax=ymax)
except ValueError:
pass
return br
修改后,蜡烛图的缩放更自然文章来源地址https://www.toymoban.com/news/detail-790184.html
到了这里,关于python_pyqtgraph蜡烛图缩放问题处理的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!