SimpleGUI 在 canvas 中显示 mpf.plot

SimpleGUI displaying mpf.plot in canvas

下面的代码会将 Matplotlib 工具栏嵌入到应用程序中,并将绘图绘制到特定的 canvas,但我想嵌入我的 mpf.plot 而不是我的 plt.plot。代码运行良好,但不会产生预期的结果,请提出任何建议

    import PySimpleGUI as sg
    import numpy as np
    import pandas as pd
    import mplfinance as mpf
    import numpy as np
    import json
    import requests


    '''
        Embedding the Matplotlib toolbar into your application
    
    '''

    import matplotlib.pyplot as plt
    from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg, NavigationToolbar2Tk
    
    
    def draw_figure_w_toolbar(canvas, fig, canvas_toolbar):
        if canvas.children:
            for child in canvas.winfo_children():
                child.destroy()
        if canvas_toolbar.children:
            for child in canvas_toolbar.winfo_children():
                child.destroy()
        figure_canvas_agg = FigureCanvasTkAgg(fig, master=canvas)
        figure_canvas_agg.draw()
        toolbar = Toolbar(figure_canvas_agg, canvas_toolbar)
        toolbar.update()
        figure_canvas_agg.get_tk_widget().pack(side='right', fill='both', expand=1)
    
    
    class Toolbar(NavigationToolbar2Tk):
        def __init__(self, *args, **kwargs):
            super(Toolbar, self).__init__(*args, **kwargs)
    
    

    
    layout = [
        [sg.T('Graph: y=sin(x)')],
        [sg.B('Plot'), sg.B('Exit')],
        [sg.T('Controls:')],
        [sg.Canvas(key='controls_cv')],
        [sg.T('Figure:')],
        [sg.Column(
            layout=[
                [sg.Canvas(key='fig_cv',
                           # it's important that you set this size
                           size=(400 * 2, 400)
                           )]
            ],
            background_color='#DAE0E6',
            pad=(0, 0)
        )],
        [sg.B('Alive?')]
    
    ]
    
    window = sg.Window('Graph with controls', layout)
    
    while True:
        event, values = window.read()
        print(event, values)
        if event in (sg.WIN_CLOSED, 'Exit'):  # always,  always give a way out!
            break
        elif event == 'Plot':


        string = 'https://api.binance.com/api/v1/klines?symbol=BTCUSDT&interval=15m'
        URL = string
        response = requests.get(url = URL)
        response = response.json()
        df = pd.DataFrame(response)
        df[0] = pd.to_datetime((df[0]), unit='ms')

        df.drop([5,6,7,8,9,10,11], axis=1, inplace=True)
        df.rename(columns={0: 'Date',1: 'Open', 2:'High', 3:'Low', 4: 'Close'}, inplace=True)
        df.index = pd.DatetimeIndex(df['Date'])
        df['Open'] = df['Open'].astype(float)
        df['High'] = df['High'].astype(float)
        df['Low'] = df['Low'].astype(float)
        df['Close'] = df['Close'].astype(float)
        df.shape
        df.head(3)
        df.tail(3)

        colors = [
        'blueskies',
         'brasil',
         'charles',
         'checkers',
         'classic',
         'default',
         'mike',
         'nightclouds',
         'sas',
         'starsandstripes',
         'yahoo'
         ]

        mpf.plot(
            df,
            type='candle',
            style= colors[10],
            title= colors[10],
            ylabel='Price ($)',
        )


        plt.figure(1)
        fig = plt.gcf()
        DPI = fig.get_dpi()

        fig.set_size_inches(404 * 2 / float(DPI), 404 / float(DPI))
        # -------------------------------
        x = np.linspace(0, 2 * np.pi)
        y = np.sin(x)
        plt.plot(x, y)
        plt.title('y=sin(x)')
        plt.xlabel('X')
        plt.ylabel('Y')
        plt.grid()

        # ------------------------------- Instead of plt.show()
        draw_figure_w_toolbar(window['fig_cv'].TKCanvas, fig, window['controls_cv'].TKCanvas)

    window.close()

将选项 returnfig=True 添加到 mpf.plot 以获得它 return fig, axlist

        fig, axlist = mpf.plot(
            df,
            type='candle',
            style= colors[10],
            title= colors[10],
            ylabel='Price ($)',
            returnfig=True,
        )

        # ------------------------------- Instead of plt.show()
        draw_figure_w_toolbar(window['fig_cv'].TKCanvas, fig, window['controls_cv'].TKCanvas)