西伯恩的Facetgrid
提供了一个方便的功能来快速将 pandas 数据帧连接到 matplotlib pyplot 接口。
然而,在 GUI 应用程序中,您很少想使用 pyplot,而是使用 matplotlib API。
你在这里面临的问题是Facetgrid
已经创建了自己的matplotlib.figure.Figure
目的 (Facetgrid.fig
)。另外,MatplotlibWidget
创建自己的图形,因此最终会得到两个图形。
现在,让我们退一步:
原则上可以使用seabornFacetgrid
在 PyQt 中绘图,首先创建绘图,然后将生成的图形提供给图形画布(matplotlib.backends.backend_qt4agg.FigureCanvasQTAgg
)。以下是如何执行此操作的示例。
from PyQt4 import QtGui, QtCore
from matplotlib.backends.backend_qt4agg import FigureCanvasQTAgg as FigureCanvas
import sys
import seaborn as sns
import matplotlib.pyplot as plt
tips = sns.load_dataset("tips")
def seabornplot():
g = sns.FacetGrid(tips, col="sex", hue="time", palette="Set1",
hue_order=["Dinner", "Lunch"])
g.map(plt.scatter, "total_bill", "tip", edgecolor="w")
return g.fig
class MainWindow(QtGui.QMainWindow):
send_fig = QtCore.pyqtSignal(str)
def __init__(self):
super(MainWindow, self).__init__()
self.main_widget = QtGui.QWidget(self)
self.fig = seabornplot()
self.canvas = FigureCanvas(self.fig)
self.canvas.setSizePolicy(QtGui.QSizePolicy.Expanding,
QtGui.QSizePolicy.Expanding)
self.canvas.updateGeometry()
self.button = QtGui.QPushButton("Button")
self.label = QtGui.QLabel("A plot:")
self.layout = QtGui.QGridLayout(self.main_widget)
self.layout.addWidget(self.button)
self.layout.addWidget(self.label)
self.layout.addWidget(self.canvas)
self.setCentralWidget(self.main_widget)
self.show()
if __name__ == '__main__':
app = QtGui.QApplication(sys.argv)
win = MainWindow()
sys.exit(app.exec_())
虽然这工作得很好,但它是否有用还是有点值得怀疑的。在大多数情况下,在 GUI 内创建绘图的目的是根据用户交互进行更新。在上面的示例中,这是非常低效的,因为它需要创建一个新的图形实例,使用该图形创建一个新的画布,并用新的画布实例替换旧的画布实例,将其添加到布局中。
请注意,这个问题特定于seaborn中的那些绘图函数,它们在图形级别上工作,例如lmplot
, factorplot
, jointplot
, FacetGrid
可能还有其他。
其他功能如regplot
, boxplot
, kdeplot
在轴级别上工作并接受 matplotlibaxes
对象作为参数(sns.regplot(x, y, ax=ax1)
).
A 可能的解决方案是首先创建子图轴,然后绘制到这些轴,例如使用pandas 绘图功能.
df.plot(kind="scatter", x=..., y=..., ax=...)
where ax
应设置为先前创建的轴。
这允许更新 GUI 内的绘图。请参阅下面的示例。当然正常的 matplotlib 绘图(ax.plot(x,y)
)或使用上面讨论的 seaborn 轴水平函数同样有效。
from PyQt4 import QtGui, QtCore
from matplotlib.backends.backend_qt4agg import FigureCanvasQTAgg as FigureCanvas
from matplotlib.figure import Figure
import sys
import seaborn as sns
tips = sns.load_dataset("tips")
class MainWindow(QtGui.QMainWindow):
send_fig = QtCore.pyqtSignal(str)
def __init__(self):
super(MainWindow, self).__init__()
self.main_widget = QtGui.QWidget(self)
self.fig = Figure()
self.ax1 = self.fig.add_subplot(121)
self.ax2 = self.fig.add_subplot(122, sharex=self.ax1, sharey=self.ax1)
self.axes=[self.ax1, self.ax2]
self.canvas = FigureCanvas(self.fig)
self.canvas.setSizePolicy(QtGui.QSizePolicy.Expanding,
QtGui.QSizePolicy.Expanding)
self.canvas.updateGeometry()
self.dropdown1 = QtGui.QComboBox()
self.dropdown1.addItems(["sex", "time", "smoker"])
self.dropdown2 = QtGui.QComboBox()
self.dropdown2.addItems(["sex", "time", "smoker", "day"])
self.dropdown2.setCurrentIndex(2)
self.dropdown1.currentIndexChanged.connect(self.update)
self.dropdown2.currentIndexChanged.connect(self.update)
self.label = QtGui.QLabel("A plot:")
self.layout = QtGui.QGridLayout(self.main_widget)
self.layout.addWidget(QtGui.QLabel("Select category for subplots"))
self.layout.addWidget(self.dropdown1)
self.layout.addWidget(QtGui.QLabel("Select category for markers"))
self.layout.addWidget(self.dropdown2)
self.layout.addWidget(self.canvas)
self.setCentralWidget(self.main_widget)
self.show()
self.update()
def update(self):
colors=["b", "r", "g", "y", "k", "c"]
self.ax1.clear()
self.ax2.clear()
cat1 = self.dropdown1.currentText()
cat2 = self.dropdown2.currentText()
print cat1, cat2
for i, value in enumerate(tips[cat1].unique().get_values()):
print "value ", value
df = tips.loc[tips[cat1] == value]
self.axes[i].set_title(cat1 + ": " + value)
for j, value2 in enumerate(df[cat2].unique().get_values()):
print "value2 ", value2
df.loc[ tips[cat2] == value2 ].plot(kind="scatter", x="total_bill", y="tip",
ax=self.axes[i], c=colors[j], label=value2)
self.axes[i].legend()
self.fig.canvas.draw_idle()
if __name__ == '__main__':
app = QtGui.QApplication(sys.argv)
win = MainWindow()
sys.exit(app.exec_())
A final word about
pyqtgraph: I wouldn't call pyqtgraph a wrapper for PyQt but more an extention. Although pyqtgraph ships with its own Qt (which makes it portable and work out of the box), it is also a package one can use from within PyQt. You can therefore add a
GraphicsLayoutWidget
to a PyQt layout simply by
self.pgcanvas = pg.GraphicsLayoutWidget()
self.layout().addWidget(self.pgcanvas)
这同样适用于MatplotlibWidget (mw = pg.MatplotlibWidget()
)。虽然您可以使用这种小部件,但它只是一个方便的包装器,因为它所做的只是找到正确的 matplotlib 导入并创建一个Figure
and a FigureCanvas
实例。除非您使用其他 pyqtgraph 功能,否则仅为了节省 5 行代码而导入完整的 pyqtgraph 包对我来说似乎有点过大了。