如何在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 这是一个可以重现的固定代码片段

# 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] close_prices = [x[4] for x in ohlcv_data] # 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.