import sys
import random
from plotnine import ggplot, geom_point, aes, geom_line, theme
import pandas as pd
import numpy as np
from PyQt5.QtWidgets import QApplication, QPushButton, QDialog, QVBoxLayout
import matplotlib.pyplot as plt
from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas
from matplotlib.backends.backend_qt5agg import NavigationToolbar2QT as NavigationToolbar
from matplotlib.figure import Figure
A PyQt5 Application
This example applicate creates a gui windows with a canvas and a plot button which when pressed draws out a plot from random data.
= 72
dpi = (11, 8) # size in inches (for the plot)
size_inches = int(size_inches[0] * dpi), int(size_inches[1] * dpi) # For the canvas
size_px
class Window(QDialog):
def __init__(self, parent=None):
super(Window, self).__init__(parent)
self.figure = Figure()
self.canvas = FigureCanvas(self.figure)
self.toolbar = NavigationToolbar(self.canvas, self)
self.button = QPushButton("Plot")
self.button.clicked.connect(self.plot)
self.canvas.setMinimumSize(*size_px)
= QVBoxLayout()
layout self.toolbar)
layout.addWidget(self.canvas)
layout.addWidget(self.button)
layout.addWidget(self.setLayout(layout)
def plot(self):
# generate some 'data' to plot
= 100
n = np.linspace(0, 2 * np.pi, n)
x = pd.DataFrame(
df
{"x": x,
"y1": np.random.rand(n),
"y2": np.sin(x),
"y3": np.cos(x) * np.sin(x),
}
)
# change the dependent variable and color each time this method is called
= random.choice(["y1", "y2", "y3"])
y = random.choice(["blue", "red", "green"])
color
# specify the plot and get the figure object
= (
ff "x", y))
ggplot(df, aes(+ geom_point(color=color)
+ geom_line()
+ theme(figure_size=size_inches, dpi=dpi)
)= ff.draw()
fig
# update to the new figure
self.canvas.figure = fig
# refresh canvas
self.canvas.draw()
# close the figure so that we don't create too many figure instances
plt.close(fig)
# To prevent random crashes when rerunning the code,
# first check if there is instance of the app before creating another.
= QApplication.instance()
app if app is None:
= QApplication(sys.argv)
app
= Window()
main
main.show() app.exec_()
0
The Application
Credit: Brad Reisfeld (@breisfeld) for putting this workflow together.