如何在pyqtgraph中正确添加日期轴

问题描述 投票:0回答:1

代码:

        self.graph = pg.PlotWidget(self)
        self.graph.setBackground("w")
        self.graph.showGrid(x=True, y=True)
        pen = pg.mkPen(color=(90, 169, 240),  width=5)
        self.graph.setYRange(0, 1000)
        self.plot = self.graph.plot(
            [],
            [],
            pen=pen,
            symbol='o',
            symbolSize=4,
            symbolBrush="b",
        )
        
        self.widgets.append(self.graph)
        
        
    def optimize_view(self):
        self.graph.setGeometry(6, 0, self.width(), self.height() - 50)
        
    def setup_graph(self, sym):
        if sym != 'USDT':
            try:
                data = self.get_price_history(self.parent().valute, self.time_frame)
            except:
                self.plot.setData([], [])
        else:
            pass
        new_date = datetime.now() - timedelta(len(data) - 1)
        
        res = pd.date_range(min(new_date, datetime.now()),max(new_date, datetime.now())).tolist()
        res = [datetime.timestamp(i) for i in res]
        axis_res = pd.date_range(min(new_date, datetime.now()),max(new_date, datetime.now())).strftime('%d.%m.%Y').tolist()
        self.graph.setYRange(min(data), max(data))
        self.graph.setXRange(min(res), max(res))
        print(len(res), len(data))
        
        date_axis = pg.graphicsItems.DateAxisItem.DateAxisItem(orientation = 'bottom')
        self.graph.setAxisItems(axisItems = {'bottom': date_axis})
        
        self.plot.setData(res, data)
        
    def get_price_history(self, symbol, timeframe):
        exchange = ccxt.binance()
        
        data = exchange.fetch_ohlcv(f'{symbol}/USDT', timeframe)
        
        prices = [candle[3] for candle in data]
        
        return prices

我的底部轴带有日期增量值。我需要将其替换为格式为“%d.%m.%Y”的字符串日期。我应该怎么办?我不明白文本轴是如何工作的。 self.graph 底轴必须仅包含 str-dates。

get_price_history
返回浮点值列表。

python pyqt pyqtgraph
1个回答
0
投票

虽然代码存在一些缺陷,但任务很明确:使用 pyqtgraph 交互式绘制通过 ccxt 在线获取的加密货币数据

对于主要问题,传递数字时间戳,例如

1717977600
翻译为
Monday, 10 June 2024 00:00:00
并使用 DateAxisItem
 将轴注释为日期

绘图是交互式的,因此,

格式取决于缩放以优化视觉体验。这意味着,放大更多以查看天数,缩小缩放以查看月份。我建议初学者继续使用它,并尝试自定义作为第二步,请参阅文档

下面,我附上了一个固定的代码片段,其中包含一个完全工作的应用程序和一个屏幕截图

enter image description here

# file name: bitcoin_plot.py # run: python bitcoin_plot.py import sys from datetime import datetime, timedelta import ccxt import pandas as pd import pyqtgraph as pg from PyQt5 import QtWidgets class BTCUSDTPlotter(QtWidgets.QWidget): def __init__(self, parent=None): super().__init__(parent) layout = QtWidgets.QVBoxLayout(self) self.graph = pg.PlotWidget() self.graph.showGrid(x=True, y=True) layout.addWidget(self.graph) def fetch_and_plot(self): # fetch BTC/USDT data from Binance exchange = ccxt.binance({'enableRateLimit': True}) symbol = 'BTC/USDT' timeframe = '1d' ohlcv_data = exchange.fetch_ohlcv(symbol, timeframe) # process timestamps = [x[0] / 1000 for x in ohlcv_data] # convert to seconds dates = [datetime.fromtimestamp(ts) for ts in timestamps] # use numeric timestamps close_prices = [x[4] for x in ohlcv_data] # https://github.com/ccxt/ccxt/blob/b6ea6bd9b88525c6110ba8f658c727b0ed6bcf62/examples/py/binance-fetch-ohlcv.py#L38 # plot self.graph.plot(timestamps, close_prices, pen=pg.mkPen(color=(0, 120, 200), width=2)) date_axis = pg.graphicsItems.DateAxisItem.DateAxisItem(orientation='bottom') self.graph.setAxisItems({'bottom': date_axis}) def main(): app = QtWidgets.QApplication(sys.argv) window = QtWidgets.QMainWindow() plotter = BTCUSDTPlotter() plotter.fetch_and_plot() window.setCentralWidget(plotter) window.show() sys.exit(app.exec_()) if __name__ == "__main__": main()
    
© www.soinside.com 2019 - 2024. All rights reserved.