首页 > 编程问答 >无法显示 mpf.plot 图表

无法显示 mpf.plot 图表

时间:2024-07-22 14:56:08浏览次数:10  
标签:python matplotlib pyqt5 mplfinance

当我通过axes.plot(x_data, y_data, label='Close Price', color='r')绘制图表时,我的程序绘制图表。但是,当我通过 mpf.plot 绘制图形时,我的程序无法绘制图形。我无法收到任何错误消息。只是不画。我的代码如下

import matplotlib.pyplot as plt
from matplotlib.figure import Figure
from matplotlib.axes import Axes
from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas

self.fig = plt.figure()
self.canvas = FigureCanvas(self.fig)
self.d_axes_mgr = DynamicSubplotManager(self.fig) ==> axes management class

try:
    required_columns = ['Open', 'High', 'Low', 'Close', 'Volume']
    for col in required_columns:
       if col not in filtered_df.columns:
          raise ValueError(f"Missing required column: {col}")

    if axes:
       print(f"Axes title: {axes.get_title()}")
       print(f"Axes xlabel: {axes.get_xlabel()}")
       print(f"Axes ylabel: {axes.get_ylabel()}")
       mpf.plot(filtered_df[-100:], type='ohlc', ax=ax, style='charles', returnfig=True, warn_too_much_data=len(filtered_df))                

       # Directly plotting the Close price with a label
       #axes.plot(x_data, y_data, label='Close Price', color='r')
       #print("Line plot completed successfully")


except ValueError as ve:
   print(f"ValueError: {ve}")
except TypeError as te:
   print(f"TypeError: {te}")
except KeyError as ke:
   print(f"KeyError: {ke}")
ex cept Exception as e:
   print(f"Unexpected error: {e}")
self.canvas.draw_idle()```



could you help me?



debugging  : axes properties below:
Axes properties: {'_stale': True, 'stale_callback': <function _stale_figure_callback at 0x0000021CC265E7A0>, '_axes': <Axes: >, 'figure': <Figure size 640x480 with 1 Axes>, '_transform': None, '_transformSet': False, '_visible': True, '_animated': False, '_alpha': None, 'clipbox': None, '_clippath': None, '_clipon': True, '_label': '', '_picker': None, '_rasterized': False, '_agg_filter': None, '_mouseover': False, '_callbacks': <matplotlib.cbook.CallbackRegistry object at 0x0000021CCFD581A0>, '_remove_method': <bound method FigureBase.delaxes of <Figure size 640x480 with 1 Axes>>, '_url': None, '_gid': None, '_snap': None, '_sketch': None, '_path_effects': [], '_sticky_edges': _XYPair(x=[], y=[]), '_in_layout': True, '_position': Bbox([[0.0, 0.050000000000000044], [0.92, 1.0]]), '_originalPosition': Bbox([[0.0, 0.050000000000000044], [0.92, 1.0]]), '_aspect': 'auto', '_adjustable': 'box', '_anchor': 'C', '_stale_viewlims': {'x': False, 'y': False}, '_forward_navigation_events': 'auto', '_sharex': None, '_sharey': None, 'bbox': <matplotlib.transforms.TransformedBbox object at 0x0000021CCD603D40>, 'dataLim': Bbox([[inf, inf], [-inf, -inf]]), '_viewLim': Bbox([[18927.375, 15781.29], [19926.375, 73072.41]]), 'transScale': <matplotlib.transforms.TransformWrapper object at 0x0000021CCF8A0B30>, 'transAxes': <matplotlib.transforms.BboxTransformTo object at 0x0000021CCFD5A150>, 'transLimits': <matplotlib.transforms.BboxTransformFrom object at 0x0000021CCF8A39B0>, 'transData': <matplotlib.transforms.CompositeGenericTransform object at 0x0000021CCF8A3290>, '_xaxis_transform': <matplotlib.transforms.BlendedGenericTransform object at 0x0000021CCF8A28D0>, '_yaxis_transform': <matplotlib.transforms.BlendedGenericTransform object at 0x0000021CCF8A0B90>, '_subplotspec': GridSpec(1, 1)[0:1, 0:1], '_box_aspect': None, '_axes_locator': None, '_children': [], '_colorbars': [], 'spines': <matplotlib.spines.Spines object at 0x0000021CCFD5AA20>, 'xaxis': <matplotlib.axis.XAxis object at 0x0000021CCF8A23F0>, 'yaxis': <matplotlib.axis.YAxis object at 0x0000021CCF8A3AA0>, '_facecolor': 'white', '_frameon': True, '_axisbelow': 'line', '_rasterization_zorder': None, 'ignore_existing_data_limits': True, 'callbacks': <matplotlib.cbook.CallbackRegistry object at 0x0000021CCD601BE0>, '_xmargin': 0.05, '_ymargin': 0.05, '_tight': None, '_use_sticky_edges': True, '_get_lines': <matplotlib.axes._base._process_plot_var_args object at 0x0000021CCF8A3B60>, '_get_patches_for_fill': <matplotlib.axes._base._process_plot_var_args object at 0x0000021CCF8A3740>, '_gridOn': False, '_mouseover_set': <matplotlib.cbook._OrderedSet object at 0x0000021CCF8A1850>, 'child_axes': [], '_current_image': None, '_projection_init': (<class 'matplotlib.axes._axes.Axes'>, {}), 'legend_': None, 'containers': [], '_autotitlepos': True, 'title': Text(0.5, 1.0, ''), '_left_title': Text(0.0, 1.0, ''), '_right_title': Text(1.0, 1.0, ''), 'titleOffsetTrans': <matplotlib.transforms.ScaledTranslation object at 0x0000021CCF9DB290>, 'patch': <matplotlib.patches.Rectangle object at 0x0000021CCF9DB380>, 'axison': True, 'fmt_xdata': None, 'fmt_ydata': None, '_navigate': True, '_navigate_mode': None}

The issue is likely with how you are managing and interacting with the Matplotlib figures and axes within your Qt environment. Here's a breakdown of the problem and a solution:

Problem:

  • Conflicting Axes: You're likely creating an initial figure and axes using self.fig = plt.figure() and then trying to plot on different axes managed by your DynamicSubplotManager (details not shown in your code). This mismatch in axes references can lead to plots not appearing.

  • Missing draw() or draw_idle() : After calling mpf.plot , you must explicitly update the canvas to reflect the changes. You've used self.canvas.draw_idle() , but it's essential to ensure it's called at the right time and in the correct context of your Qt event loop.

Solution:

  1. Consistent Axes Handling:

  2. Method 1: Integrate with DynamicSubplotManager :

    • Modify DynamicSubplotManager to accept an existing figure or axes during initialization.
    • Pass self.fig or the desired axes to DynamicSubplotManager so it controls the axes used for plotting.
  3. Method 2: Direct Control:

    • If DynamicSubplotManager isn't strictly necessary, get the axes directly from your figure: python ax = self.fig.add_subplot(111) # For a single subplot mpf.plot(filtered_df[-100:], type='ohlc', ax=ax, style='charles', returnfig=True, warn_too_much_data=len(filtered_df))
  4. Canvas Update: Ensure self.canvas.draw_idle() is called after the mpf.plot function to refresh the canvas.

Revised Code Structure (Illustrative):

import matplotlib.pyplot as plt
from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas
import mplfinance as mpf  # Import mplfinance

# ... other imports and your DynamicSubplotManager class definition ...

class YourWidget(QtWidgets.QWidget):  # Or your Qt widget class
    def __init__(self):
        # ... your initialization ...

        self.fig = plt.figure()
        self.canvas = FigureCanvas(self.fig)

        # Assuming DynamicSubplotManager can work with an existing figure
        self.d_axes_mgr = DynamicSubplotManager(self.fig)  

    def update_plot(self, filtered_df):
        try:
            # ... (Your data validation code) ...

            # Get the correct axes from your DynamicSubplotManager
            axes = self.d_axes_mgr.get_axes("your_subplot_key")  

            if axes:
                mpf.plot(filtered_df[-100:], type='ohlc', ax=axes, style='charles', 
                         returnfig=True, warn_too_much_data=len(filtered_df)) 

                # Refresh the canvas
                self.canvas.draw_idle() 

        except Exception as e:
            print(f"Error in plotting: {e}") 

Key Points:

  • Import mplfinance: Ensure you have mplfinance installed ( pip install mplfinance ) and imported correctly.
  • Error Handling: Use try-except blocks to catch potential errors during plotting for better debugging.
  • Qt Integration: The code provided assumes integration with a Qt application. Adapt it based on your specific Qt widget structure.
  • DynamicSubplotManager: Without the implementation details of DynamicSubplotManager , the example provides a general approach. You'll need to adjust how you obtain the correct axes from it.

By carefully managing axes and ensuring canvas updates, your mpf.plot calls should work correctly within your Qt application.

标签:python,matplotlib,pyqt5,mplfinance
From: 78777300

相关文章

  • MIT自学---python---6.100A_lecture2
    MIT自学---python---6.100A_lecture2前言一、设置python编译器地址二、将运行python文件的命令简化三、终端尝试执行简单python命令四、今日学到的python命令个人总结前言  这两天去听讲座,没什么时间按照计划自学MIT,今天赶紧补上。今天主要任务是搭建vscodepython......
  • python pip 需要构建工具,而它已经安装
    我看到这个问题已经被发布了很多次,人们设法解决了这个问题,但我没有!!操作系统版本:Windows1021H1Build19043.1288Python版本:Python3.9.7(tags/v3.9.7:1016ef3,Aug302021,20:19:38)[MSCv.192964bit(AMD64)]onwin32Pip、wheel和setuptool都可以日期:......
  • 无法在浏览器中访问Python 127.0.0.1:8000上的本地主机
    fromdjango.contribimportadminfromdjango.urlsimportpath,includeurlpatterns=[path('admin/',admin.site.urls),path('products/'),include('products.urls')#thisline]嗨,任何人。很抱歉问这样的问题,但这是我第一次尝试python。......
  • 在 VSCode 中通过 Python 使用 YouTube API 时如何启用 Intellisense
    我想在使用GoogleYouTubeAPI和Python时在VSCode中获得IntelliSense。但我不知道详细步骤。fromgoogleapiclient.discoveryimportbuildapi_key="****"youtube=build("youtube","v3",developerKey=api_key)request=youtube.channels().list(part......
  • 当 python 脚本通过 jenkins + Github 在 Windows 本地计算机上运行时,chrome 浏览器不
    我的Python代码是(windowsMachine)fromseleniumimportwebdriverprint("newLine")print("2Line")print("3Line")holdChrome=webdriver.ChromeOptions()holdChrome.add_experimental_option("detach",True)#Restricta......
  • python_基础_数据类型
    基础数据类型不需要声明,只有被赋值后才会创建变量。变量本身没有类型,“类型”指的是所存值的类型。类型判断type(x)和isinstance(x,int)前者不会认为子类是一种他的父类类型后者会认为子类是父类类型>>>classA:...pass...>>>classB(A):...pass......
  • IPython 使用技巧
    IPython是一个强大的交互式Pythonshell,提供了许多方便的功能,使Python编程更加高效和愉快。本文将介绍一些IPython的实用技巧,帮助开发者充分利用其功能,提高编程效率。1.基本操作和快捷键1.1启动IPython可以通过在终端输入以下命令来启动IPython:ipython启动后,你......
  • 【python】类方法和静态方法的区别
    类方法和静态方法在Python中都可以用来定义与类相关的功能,但它们有不同的使用场景和优缺点。虽然类方法也可以用来实现验证逻辑,但静态方法在某些情况下更合适。让我们详细看看这两种方法的区别以及为什么在某些情况下静态方法可能更适合验证功能。类方法和静态方法的区别类......
  • Python自动化:一键提取千万个Excel指定数据
    一、传统方法的局限性打开每个Excel文件,逐个查找需要的数据。筛选出老板需要的数据列。复制并粘贴到新的工作表中。保存并关闭每个文件。这个过程不仅耗时,而且容易出错。每一次的筛选都可能遗漏数据,每一次的复制粘贴都可能引入错误。二、Python自动化的解决方案i......
  • Python:提交和跟踪许多子流程会导致“卡住”子流程
    我有一个第3方cli可执行文件,需要从python代码中调用。这些都是繁重的计算(CPU),我需要调用它大约50-100次。可执行文件本身在某种程度上是多线程的,但不是所有步骤,而且我有很多可用的核心。这意味着我希望同时运行多个子进程,但不是全部。因此,我需要提交其中一些,然后跟踪......