Python 3.x 如何使用pyqtgraph和pyqt5设置蜡烛棒中的轴间距?

Python 3.x 如何使用pyqtgraph和pyqt5设置蜡烛棒中的轴间距?,python-3.x,pyqt5,pyqtgraph,Python 3.x,Pyqt5,Pyqtgraph,我正在使用pyqtgraph绘制蜡烛棒,如下所示: #------------------- # Create pyqtgraph module #------------------- def GUI_DRAW_create(): """ set default config """ pg.setConfigOption('background', 'w') #background: white

我正在使用pyqtgraph绘制蜡烛棒,如下所示:

#-------------------
# Create pyqtgraph module 
#------------------- 
def GUI_DRAW_create():
    """
    set default config
    """
    pg.setConfigOption('background', 'w')   #background: white
    pg.setConfigOption('foreground', 'k')   #font: black

class TimeAxisItem(pg.AxisItem):
    def tickStrings(self, values, scale, spacing):
        #values is not my date in timestamp 
        return [datetime.fromtimestamp(value) for value in values]
    
## Create a subclass of GraphicsObject.
## The only required methods are paint() and boundingRect() 
## (see QGraphicsItem documentation)
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('k'))
        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()
        # I try to print out t here, is my date 
    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())
        
        
class GUI_DRAW_new(QMainWindow):
    def __init__(self):
        super().__init__()
        
        GUI_DRAW_create()
        
        self.setWindowTitle("pyqtgraph example: PlotWidget")
        
        cw = QWidget()
        self.setCentralWidget(cw)
        
        main_layout = QHBoxLayout()
        cw.setLayout(main_layout)
        
        #variable 
        self.signalgraph = None
        self.data = []
        self.vb = None
        self.vLine = None
        
        # define plot windows
        self.GUI_DRAW_new_graph()
        main_layout.addWidget(self.signalgraph)
        
        self.signalgraph.setMouseTracking(True)
        self.signalgraph.viewport().installEventFilter(self)
        
        self.show()

    def eventFilter(self, source, event):
        try:
            if (event.type() == QtCore.QEvent.MouseMove and
                source is self.signalgraph.viewport()):
                pos = event.pos()
                print('mouse move: (%d, %d)' % (pos.x(), pos.y()))
                if self.signalgraph.sceneBoundingRect().contains(pos):
                    mousePoint = self.vb.mapSceneToView(pos)
                    index = int(mousePoint.x())
                    int(index)
                    #if index > 0 and index < len(self.data):
                        #print(self.xdict[index])
                        
                    #    self.label.setHtml("<p style='color:black'>日期:{0}</p>".format(self.data[index]))
                    #    self.label.setPos(mousePoint.x(),mousePoint.y())
                    self.vLine.setPos(mousePoint.x())
                    
            return QtGui.QWidget.eventFilter(self, source, event)
        except Exception as e:
            traceback.print_exc()
            err = sys.exc_info()[1]
            PRINT_DEBUG(0,str(err))
            
    def GUI_DRAW_new_graph(self):
        try:
            self.signalgraph = pg.PlotWidget(name="Signalgraph", axisItems={'bottom': TimeAxisItem(orientation='bottom')})
            
            # sample data
            self.data = [  ## fields are (time, open, close, min, max).
                (1514995200.0, 102.610001, 105.349998, 102, 105.370003),
                (1515081600.0, 105.75, 102.709999, 102.410004, 105.849998),
                (1515168000.0, 100.559998, 102.370003, 99.870003, 100.699997),
                (1515254400.0, 98.68, 96.449997, 96.43, 100.129997),
                (1515340800.0, 98.550003, 96.959999, 96.760002, 99.110001),
                
                (1515427200.0, 102.610001, 105.349998, 102, 105.370003),
                (1515513600.0, 105.75, 102.709999, 102.410004, 105.849998),
                (1515600000.0, 100.559998, 102.370003, 99.870003, 100.699997),
                (1515686400.0, 98.68, 96.449997, 96.43, 100.129997),
                (1515772800.0, 98.550003, 96.959999, 96.760002, 99.110001),
            ]
            
            #if comment this 2 code, can see the string
            item = CandlestickItem(self.data)
            self.signalgraph.addItem(item)
            
            #trick
            s_day = datetime.fromtimestamp(self.data[0][0]).strftime("%Y-%m-%d")
            e_day = datetime.fromtimestamp(self.data[len(self.data) - 1][0]).strftime("%Y-%m-%d")
            tr=np.arange(s_day, e_day, dtype='datetime64') # tick labels one day 
            
            tday0=(tr-tr[0])/(tr[-1]-tr[0])  #Map time to 0.0-1.0 day 2 1.0-2.0 ...
            tday1=tday0+1
        
            tnorm=np.concatenate([tday0,tday1])
            tr[-1]=tr[0]  # End day=start next day
            
            ttick=list()    
            for i,t in enumerate(np.concatenate([tr,tr])):
                tstr=np.datetime64(t).astype(datetime)
                ttick.append(  (tnorm[i],  tstr.strftime("%Y-%m-%d")))  
        
            ax=self.signalgraph.getAxis('bottom')    #This is the trick  
            ax.setTicks([ttick])
            #cross hair in signalgraph
            self.vLine = pg.InfiniteLine(angle=90, movable=False)
            self.signalgraph.addItem(self.vLine, ignoreBounds=True)
            self.vb = self.signalgraph.plotItem.vb
            
        except Exception as e:
            traceback.print_exc()
            err = sys.exc_info()[1]
            print(0,str(err))
                        

# Start Qt event loop unless running in interactive mode or using pyside.
if __name__ == "__main__":
    app = QtGui.QApplication([])
    gui = GUI_DRAW_new()
    app.exec_()
#-------------------
#创建pyqtgraph模块
#------------------- 
def GUI_DRAW_create():
"""
设置默认配置
"""
pg.setConfigOption('background','w')#背景:白色
pg.setConfigOption('前景','k')#字体:黑色
类TimeAxisItem(pg.AxisItem):
def勾选字符串(自身、值、比例、间距):
#值不是时间戳中的日期
return[datetime.fromtimestamp(value)表示值中的值]
##创建GraphicsObject的子类。
##唯一需要的方法是paint()和boundingRect()
##(参见QGraphicsItem文档)
烛台类(图形主题页):
定义初始化(自身,数据):
pg.GraphicsObject.\uuuuuu初始\uuuuuuuuuuuuuu(自)
self.data=数据##数据必须包含以下字段:时间、打开、关闭、最小值、最大值
self.generatePicture()
def生成结构(自身):
##预计算QPicture对象可以让paint()更快地运行,
##而不是每次都重新绘制形状。
self.picture=QtGui.QPicture()
p=QtGui.QPainter(self.picture)
p、 设置笔(pg.mkPen('k'))
w=(self.data[1][0]-self.data[0][0])/3。
对于self.data中的(t、打开、关闭、最小值、最大值):
p、 抽绳(QtCore.QPointF(t,最小值),QtCore.QPointF(t,最大值))
如果打开>关闭:
p、 立根刷(pg.mkBrush('r'))
其他:
p、 立根刷(pg.mkBrush('g'))
p、 drawRect(QtCore.QRectF(t-w,打开,w*2,关闭-打开))
p、 完()
#我试着在这里打印t,这是我的约会
def油漆(自身、p、*参数):
p、 drawPicture(0,0,self.picture)
def boundingRect(自):
##boundingRect u必须u指示将在其上绘制的整个区域
##否则我们将得到人工制品,并可能崩溃。
##(在本例中,QPicture为我们完成计算bouning rect的所有工作)
返回QtCore.QRectF(self.picture.boundingRect())
类GUI\u DRAW\u new(QMainWindow):
定义初始化(自):
super()。\uuuu init\uuuuu()
GUI_绘制_创建()
setWindowTitle(“pyqtgraph示例:PlotWidget”)
cw=QWidget()
self.setCentralWidget(cw)
main_layout=QHBoxLayout()
连续设置布局(主布局)
#变数
self.signalgraph=None
self.data=[]
self.vb=无
self.vLine=None
#定义打印窗口
self.GUI\u DRAW\u new\u graph()
main_layout.addWidget(self.signalgraph)
self.signalgraph.setMouseTracking(True)
self.signalgraph.viewport().installEventFilter(self)
self.show()
def eventFilter(自身、源、事件):
尝试:
if(event.type()==QtCore.QEvent.MouseMove和
源是self.signalgraph.viewport()):
pos=event.pos()
打印('鼠标移动:(%d,%d)'(位置x(),位置y())
如果self.signalgraph.sceneboundingdirect()包含(pos):
mousePoint=self.vb.MapScenetView(pos)
index=int(mousePoint.x())
int(索引)
#如果索引>0且索引日期:{0}

“.format(self.data[index])) #self.label.setPos(mousePoint.x(),mousePoint.y()) self.vLine.setPos(mousePoint.x()) 返回QtGui.QWidget.eventFilter(self、source、event) 例外情况除外,如e: traceback.print_exc() err=sys.exc_info()[1] 打印调试(0,str(err)) 定义图形用户界面绘制新图形(自): 尝试: self.signalgraph=pg.PlotWidget(name=“signalgraph”,axisItems={'bottom':TimeAxisItem(orientation='bottom')) #样本数据 self.data=[##字段为(时间、打开、关闭、最小值、最大值)。 (1514995200.0, 102.610001, 105.349998, 102, 105.370003), (1515081600.0, 105.75, 102.709999, 102.410004, 105.849998), (1515168000.0, 100.559998, 102.370003, 99.870003, 100.699997), (1515254400.0, 98.68, 96.449997, 96.43, 100.129997), (1515340800.0, 98.550003, 96.959999, 96.760002, 99.110001), (1515427200.0, 102.610001, 105.349998, 102, 105.370003), (1515513600.0, 105.75, 102.709999, 102.410004, 105.849998), (1515600000.0, 100.559998, 102.370003, 99.870003, 100.699997), (1515686400.0, 98.68, 96.449997, 96.43, 100.129997), (1515772800.0, 98.550003, 96.959999, 96.760002, 99.110001), ] #如果注释这2个代码,可以看到字符串 项目=烛台KITEM(自我数据) self.signalgraph.addItem(项目) #诡计 s_day=datetime.fromtimestamp(self.data[0][0]).strftime(“%Y-%m-%d”) e_day=datetime.fromtimestamp(self.data[len(self.data)-1][0]).strftime(“%Y-%m-%d”) tr=np.arange(s_-day,e_-day,dtype='datetime64')#勾选标签一天 tday0=(tr-tr[0])/(tr[-1]-tr[0])#将时间映射到0.0-1.0天21.0-2.0。。。 tday1=tday0+1 tnorm=np.concatenate([tday0,tday1]) tr[-1]=tr[0]#结束日=第二天开始 ttick=list() 对于枚举中的i,t(np.concatenate([tr,tr]): tstr=np.datetime64(t).astype(datetime) ttick.append((tnorm[i],tstr.strftime(“%Y-%m-%d”)) ax=self.signalgraph.getAxis('bottom')#这就是诀窍
from datetime import datetime

class TimeAxisItem(pg.AxisItem):
    def tickStrings(self, values, scale, spacing):
        #values is not my date in timestamp 
        return [datetime.fromtimestamp(value).strftime("%Y-%m-%d") for value in values]
from datetime import date

class TimeAxisItem(pg.AxisItem):
    def tickStrings(self, values, scale, spacing):
        #values is not my date in timestamp 
        return [date.fromtimestamp(value) for value in values]
from datetime import datetime

class TimeAxisItem(pg.AxisItem):
    def tickStrings(self, values, scale, spacing):
        #values is not my date in timestamp 
        return [datetime.fromtimestamp(value).date() for value in values]