I am currently preparing a window that should show mplfinance plots whenever I send a new dataset to my "MyDynamicMplCanvas". So far the solution works and also the Toolbar is linked to the current content of the canvas. My problem is that I want to print volume, too. Which is part of my pandas dataframe. But just setting volume = True brings the error:
ValueError: volume
must be of type matplotlib.axis.Axes
. Here is my code:
import sys
import pandas as pd
import mplfinance as mpf
from PyQt5.QtWidgets import QApplication, QWidget, QVBoxLayout, QSizePolicy, QPushButton
from matplotlib.backends.backend_qt5agg import (
FigureCanvasQTAgg as FigureCanvas,
NavigationToolbar2QT as NavigationToolbar)
import matplotlib.pyplot as plt
class MyMplCanvas(FigureCanvas):
def __init__(self, parent=None, width=5, height=4, dpi=100):
self.fig, self.ax = plt.subplots(figsize=(width, height), dpi=dpi)
super().__init__(self.fig)
self.setParent(parent)
class MyDynamicMplCanvas(QWidget):
def __init__(self, parent=None):
super().__init__(parent)
self.plot1_button = QPushButton("Plot 1")
self.plot1_button.clicked.connect(self.plot1)
self.plot2_button = QPushButton("Plot 2")
self.plot2_button.clicked.connect(self.plot2)
self.canvas = MyMplCanvas(self, width=5, height=4, dpi=100)
self.toolbar = NavigationToolbar(self.canvas, self)
vbox = QVBoxLayout()
vbox.addWidget(self.toolbar)
vbox.addWidget(self.canvas)
vbox.addWidget(self.plot1_button)
vbox.addWidget(self.plot2_button)
self.setLayout(vbox)
def getData(self, iisin):
if iisin == 'A':
pfad = '/path/to/file/Qt/DE000A0DJ6J9_4qs.csv'
else:
pfad = '/path/to/file/Qt/DE000A0DJ6J9_2qs.csv'
data = pd.read_csv(pfad, header=0, sep='|', encoding='utf-8')
data.index = pd.to_datetime(data['Datum'])
data.rename(columns={'TradesSum': 'Volume'}, inplace=True)
return data
def plot1(self):
# Start plot, after clearing the canvas
self.canvas.ax.clear()
mpf.plot(data = self.getData('A'), ax = self.canvas.ax,
type='candle', style='yahoo',
mav=(20, 38, 50), volume=False, returnfig=True)
# When volume=True this error
# ValueError: `volume` must be of type `matplotlib.axis.Axes`
# Reconnect NavigationToolbar
self.toolbar.update()
# Show plot on canvas
self.canvas.draw()
def plot2(self):
# Delete plots
self.canvas.ax.clear()
# Add plot from csv file
data = self.getData('B')
mpf.plot(data = data, ax = self.canvas.ax,
type='candle', style='yahoo',
mav=(20, 38, 50), volume=False, returnfig=True)
# Reconnect NavigationToolbar
self.toolbar.update()
# Show plot on canvas
self.canvas.draw()
if __name__ == '__main__':
app = QApplication(sys.argv)
main_window = QWidget()
main_layout = QVBoxLayout()
main_window.setLayout(main_layout)
mpl_widget = MyDynamicMplCanvas()
main_layout.addWidget(mpl_widget)
main_window.show()
sys.exit(app.exec_())
Any ideas what chatgpt did wrong? ;-)