PyQt And MatPlotLib - (Embedded) Pie Chart without PyPlot

匿名 (未验证) 提交于 2019-12-03 02:41:02

问题:

I want to embed a pie chart of data produced by an analytics class method in my PyQt GUI. Using PyPlot or PyLab I have been able to plot the chart but only in a separate window.

class MyMplCanvas(FigureCanvas):      def __init__(self, parent=None, width=5, height=4, dpi=100):         fig = Figure(figsize=(width, height), dpi=dpi)         self.axes = fig.add_subplot(111)          self.compute_initial_figure()          FigureCanvas.__init__(self, fig)         self.setParent(parent)          FigureCanvas.setSizePolicy(self,                                    QtGui.QSizePolicy.Expanding,                                    QtGui.QSizePolicy.Expanding)         FigureCanvas.updateGeometry(self) 

Above is the canvas in which the pie chart should be displayed. I think I must use the self.axes parameter in embedding the chart but I don't know. Below is the code I have thus far for the pie chart:

class UsersPlatformPie(MyMplCanvas):      def compute_initial_figure(self):          UsersPerCountry, UsersPerPlatform = Analytics.UsersPerCountryOrPlatform()         labels = []         sizes = []         print UsersPerPlatform         for p, c in sorted(UsersPerPlatform.iteritems()):             labels.append(p)             sizes.append(c)         colors = ['turquoise', 'yellowgreen', 'firebrick', 'lightsteelblue', 'royalblue']         pylab.pie(sizes, colors = colors, labels = labels, autopct = '%1.1f%%', shadow = True)         pylab.title('Users Per Platform')         pylab.gca().set_aspect('1'); pylab.show() 

I think this is superfluous but below is the establishment of the widget.

class Ui_MainWindow(object):     def setupUi(self, MainWindow):         ...         self.main_widget = QtGui.QWidget(MainWindow)         l = QtGui.QVBoxLayout(self.main_widget)         UPP = UsersPlatformPie(self.main_widget, width=5, height=4, dpi=100)         l.addWidget(UPP)         self.main_widget.setFocus()         MainWindow.setCentralWidget(self.main_widget) 

I am basing this code on this. I apologise for the code heavy nature of this question but I think at least the first two segments are necessary. Advice on either a new way of plotting the pie chart or connecting my pie chart to the canvas above will be much appreciated.

回答1:

You normally want to avoid using pyplot in a GUI application. So if I understand correctly the UsersPlatformPie subclasses MyMplCanvas, which means that you have the axes to plot on available as self.axes.

Therefore do

self.axes.pie(sizes, colors = colors, labels = labels, autopct = '%1.1f%%', shadow = True) self.axes.set_title('Users Per Platform') self.axes.set_aspect('1') self.axes.figure.canvas.draw() 


标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!