python_pyqtgraph蜡烛图缩放问题处理

写在前面:

pyqtgraph包中现有的例子中,蜡烛图的缩放不是很好用。这里做了一些修改,使用起来更自然些。

放置蜡烛图控件的父容器设置

v.setMouseEnabled(x=True, y=False)
v.setAutoVisible(x=False, y=True)

修改后的蜡烛图控件

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

修改后,蜡烛图的缩放更自然

你可能感兴趣的:(python杂项,python,pyqtgraph)