pyqtgraph数据可视化3:使用PyQtGraph绘制精美折线图——以上证指数为例(转载)

# coding:utf-8
import pyqtgraph as pg
import tushare as ts
import numpy as np

if __name__ == '__main__':
    data = ts.get_hist_data('sh', start='2021-08-09', end='2021-09-08').sort_index()
    xdict = dict(enumerate(data.index))

    axis_1 = [(i, list(data.index)[i]) for i in range(0, len(data.index), 5)]

    app = pg.QtGui.QApplication([])
    win = pg.GraphicsWindow(title='州的先生zmister.com pyqtgraph数据可视化 - 绘制精美折线图')
    #通过之前创建的字典xdict和列表axis_1,设置图形的X坐标轴刻度文本,orientation参数表示坐标轴的位置
    stringaxis = pg.AxisItem(orientation='bottom')
    stringaxis.setTicks([axis_1, xdict.items()])
    #在窗口中添加一个空的图形,通过axisItems参数指定坐标轴及其内容,并使用title参数设置了图形的标题
    plot = win.addPlot(axisItems={'bottom': stringaxis},title='上证指数 - zmister.com绘制')
    #在图形中添加一个文本
    label = pg.TextItem()
    plot.addItem(label)
    #设置图形的图例
    plot.addLegend(size=(150, 80))
    #设置图形网格的形式,我们设置显示横线和竖线,并且透明度惟0.5
    plot.showGrid(x=True, y=True, alpha=0.5)
    #绘制开盘和收盘的指数,pen参数表示线的颜色,name参数可用于图例的显示,symbolBrush用来设置点的颜色
    plot.plot(x=list(xdict.keys()), y=data['open'].values, pen='r', name='开盘指数', symbolBrush=(255, 0, 0), )
    plot.plot(x=list(xdict.keys()), y=data['close'].values, pen='g', name='收盘指数', symbolBrush=(0, 255, 0))

    #设置图形的轴标签
    plot.setLabel(axis='left', text='指数')
    plot.setLabel(axis='bottom', text='日期')

    #设置十字光标
    vLine = pg.InfiniteLine(angle=90, movable=False, )
    hLine = pg.InfiniteLine(angle=0, movable=False, )
    plot.addItem(vLine, ignoreBounds=True)
    plot.addItem(hLine, ignoreBounds=True)
    vb = plot.vb

    def mouseMoved(evt):
        pos = evt[0]  ## using signal proxy turns original arguments into a tuple
        if plot.sceneBoundingRect().contains(pos):
            mousePoint = vb.mapSceneToView(pos)
            index = int(mousePoint.x())
            pos_y = int(mousePoint.y())
            #print(index)
            if 0 < index < len(data.index):
                print(xdict[index], data['open'][index], data['close'][index])
                label.setHtml(
                    "<p style='color:white'>日期:{0}</p><p style='color:white'>开盘:{1}</p><p style='color:white'>收盘:{2}</p>".format(
                        xdict[index], data['open'][index], data['close'][index]))
                label.setPos(mousePoint.x(), mousePoint.y())
            vLine.setPos(mousePoint.x())
            hLine.setPos(mousePoint.y())


    proxy = pg.SignalProxy(plot.scene().sigMouseMoved, rateLimit=60, slot=mouseMoved)

    app.exec()
全部代码

 

在上两篇文章中,我们介绍了:

在了解了基本的PyQtGraph模块绘制图形功能之后,我们通过几个常用常见的数据可视化图形来演示使用PyQtGraph进行Python数据可视化。

本篇,我们介绍使用PyQtGraph模块绘制一个完整的折线图,通过tushare模块获取上证指数过去两个月的指数波动数据作为数据源。

下面我们分步骤讲解这个折线图形的绘制。

 

引入相关模块

在本例中,我们需要使用到pyqtgraph模块、numpy模块和tushare模块。

import pyqtgraph as pg
import tushare as ts
import numpy as np

获取数据源

我们使用tushare模块的get_hist_data()方法获取上证指数从2017年10月到2017年12月的历史行情数据:

data = ts.get_hist_data('sh',start='2017-10-01',end='2017-12-01').sort_index()

返回的是一个Pandas的DataFrame数据结构,操作起来很方便。

处理数据源

在获取到上证指数的历史行情数据之后,我们需要对其进行一些处理,以方便其后进行坐标轴刻度文本的设置。

首先,将data的日期索引转换为一个字典:

xdict = dict(enumerate(data.index))

再按5步长来去data的索引,生成一个包含索引序号和索引值元组的列表:

axis_1 = [(i,list(data.index)[i]) for i in range(0,len(data.index),5)]

绘制图形

在稍微处理好数据源之后,我们就可以进行图形绘制了。

首先实例化一个QT实例:

app = pg.QtGui.QApplication([])

接着借助GraphicsWindow()子模块创建一个空的图形窗口,并使用title参数设置了窗口的标题:

win = pg.GraphicsWindow(title='州的先生zmister.com pyqtgraph数据可视化 - 绘制精美折线图')

通过之前创建的字典xdict和列表axis_1,设置图形的X坐标轴刻度文本,orientation参数表示坐标轴的位置:

stringaxis = pg.AxisItem(orientation='bottom')
stringaxis.setTicks([axis_1,xdict.items()])

在窗口中添加一个空的图形,通过axisItems参数指定坐标轴及其内容,并使用title参数设置了图形的标题:

plot = win.addPlot(axisItems={'bottom': stringaxis},title='上证指数 - zmister.com绘制')

在图形中添加一个文本:

label = pg.TextItem()
plot.addItem(label)

设置图形的图例:

plot.addLegend(size=(150,80))

设置图形网格的形式,我们设置显示横线和竖线,并且透明度惟0.5:

plot.showGrid(x=True, y=True, alpha=0.5)

绘制开盘和收盘的指数,pen参数表示线的颜色,name参数可用于图例的显示,symbolBrush用来设置点的颜色:

plot.plot(x=list(xdict.keys()), y=data['open'].values, pen='r', name='开盘指数',symbolBrush=(255,0,0),)
plot.plot(x=list(xdict.keys()), y=data['close'].values, pen='g', name='收盘指数',symbolBrush=(0,255,0))

设置图形的轴标签:

plot.setLabel(axis='left',text='指数')
plot.setLabel(axis='bottom',text='日期')

最后设置十字光标:

vLine = pg.InfiniteLine(angle=90, movable=False,)
hLine = pg.InfiniteLine(angle=0, movable=False,)
plot.addItem(vLine, ignoreBounds=True)
plot.addItem(hLine, ignoreBounds=True)
vb = plot.vb
def mouseMoved(evt):
    pos = evt[0]  ## using signal proxy turns original arguments into a tuple
    if plot.sceneBoundingRect().contains(pos):
        mousePoint = vb.mapSceneToView(pos)
        index = int(mousePoint.x())
        pos_y = int(mousePoint.y())
        print(index)
        if 0 < index < len(data.index):
            print(xdict[index],data['open'][index],data['close'][index])
            label.setHtml("<p style='color:white'>日期:{0}</p><p style='color:white'>开盘:{1}</p><p style='color:white'>收盘:{2}</p>".format(xdict[index],data['open'][index],data['close'][index]))
            label.setPos(mousePoint.x(),mousePoint.y())
        vLine.setPos(mousePoint.x())
        hLine.setPos(mousePoint.y())
proxy = pg.SignalProxy(plot.scene().sigMouseMoved, rateLimit=60, slot=mouseMoved)

再按常例,调用app的exec()方法即可:

app.exec()

最终运行程序,绘制出来的图表如下所示:

动图如下所示:

 

是不是很简单
有问题欢迎留言讨论:)

posted @ 2021-09-09 14:16  泽良_小涛  阅读(664)  评论(0编辑  收藏  举报