【问题标题】:PyQt And MatPlotLib - (Embedded) Pie Chart without PyPlotPyQt 和 MatPlotLib - 没有 PyPlot 的(嵌入式)饼图
【发布时间】:2017-08-16 07:07:33
【问题描述】:

我想在我的 PyQt GUI 中嵌入由分析类方法生成的数据饼图。使用 PyPlot 或 PyLab 我已经能够绘制图表,但只能在单独的窗口中。

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)

上面是应该显示饼图的画布。我想我必须在嵌入图表时使用 self.axes 参数,但我不知道。以下是我迄今为止的饼图代码:

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()

我觉得这是多余的但是下面是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)

我将此代码基于this。对于这个问题的代码繁重,我深表歉意,但我认为至少前两个部分是必要的。非常感谢有关绘制饼图的新方法或将我的饼图连接到上面的画布的建议。

【问题讨论】:

  • 你不应该为显示太多代码而道歉,而应该为没有显示minimal reproducible example而道歉。
  • 我没有这样做的原因是这不是一个错误。中间部分确实有效,只是不是以预期的方式。
  • 这不是错误,而是不受欢迎的行为。尤其是当您链接到显示正确行为的问题时,确实需要minimal reproducible example 才能重现该问题。

标签: python matplotlib pyqt embed pie-chart


【解决方案1】:

您通常希望避免在 GUI 应用程序中使用 pyplot。因此,如果我正确理解了UsersPlatformPie 子类MyMplCanvas,这意味着您可以使用self.axes 来绘制坐标轴。

所以

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()

【讨论】:

  • 我尝试了这种方法,因为它也在链接的文档中使用,但我得到一个“'NoneType' object has no attribute 'draw'”错误。
  • 哦哈。现在我们有一个错误。因此,您希望我(或其他任何人)在无法访问 minimal reproducible example 的情况下解决它,这就是您的意思吗?
  • 我已经为您的答案提交了一个编辑,它产生了所需的结果,只是删除了最后一行。感谢您的帮助。
  • 如果最后一行不起作用,则您的应用程序中的其他内容不正确。
  • 如果我遇到这样的问题,我将使用 MCV 示例更新此查询。
猜你喜欢
  • 1970-01-01
  • 2013-04-17
  • 1970-01-01
  • 2017-08-24
  • 1970-01-01
  • 1970-01-01
  • 2016-07-05
  • 1970-01-01
  • 2021-11-11
相关资源
最近更新 更多